How can I access the attributes of an element by using JS?

How can I access the attributes of an element by using JS? I tried (example) element.style.width. I only need the numeric value, I mean 50 instead 50px.

3 answers

  • answered 2018-02-13 02:20 Shanon Jackson

    element.offsetWidth will give you the width as a numeric value.

    Alternatively you could use element.style.width and parse it into a number with

    Number.parseInt("50px")
    

    or the faster bitwise version

    ~~("50px".replace("px", ""))
    

  • answered 2018-02-13 02:20 Mike Ezzati

    Use window.getComputedStyle(element).width

  • answered 2018-02-13 02:20 Lex

    In this way...

    let theD = document.getElementById('theDiv');
    theD.innerHTML = theD.offsetWidth;
    #theDiv {
      width: 50px;
      height: 50px;
      background-color: coral;
    }
    <div id="theDiv"></div>