-1

I tried to access the width of a div using javascript, but every time it is printing NaN no matter what i set it. I am new to javascript, what is wrong with my code ?

    <html>
    <head>
        <title>hello</title>


        <style type="text/css">

      #base
      {
        width:300px;
        height:30px;
        background-color: black;
      }

      #scr
      {
        height:30px;
        width:10px;
        background-color: red;
      }

    </style>


    <script type="text/javascript">

    var magic = function()
    {
    console.log("inside magic")
    var d = document.getElementById("scr");
    var b =  d.style.width;
    console.log(b);
    b = parseInt(b);

    console.log(b);

    }


    </script>

    </head>

    <body>

    <div id="base">
    <div id = "scr" >
    </div>
    </div>

    <br>
    <button onclick="magic()">Magic</button>


    </body>
</html>
user1263375
  • 663
  • 3
  • 18
  • 35
  • 1
    @user1263375: I don't see the accepted answer using jQuery. And the answer you accepted now is the same as the one from the other question. – Felix Kling Feb 16 '13 at 21:06
  • The style property is actually the attribute style of the element. So when you have element.style is actually referencing what is contained in style. In your case, if you had ...style="width:20px;" then element.style would print 20px. – Magic Lasso Dec 24 '13 at 17:51
  • What you are wanting is not an attribute but rather a calculated property of the element itself. In this case, with plain javascript its often easiest to use width = element.offsetWidth || element.clientWidth || element.scrollHeight; – Magic Lasso Dec 24 '13 at 17:52

3 Answers3

1

You can use this function to do that:

function getStyle(el,styleProp)
{
    var x = document.getElementById(el);
    if (x.currentStyle)
        var y = x.currentStyle[styleProp];
    else if (window.getComputedStyle)
        var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
    return y;
}

The explanation of what's going on is here Note that you must use element's id to access its style property through the function. If you want to use selectors use document.querySelector() in place of document.getElementById()

paperstreet7
  • 2,058
  • 1
  • 15
  • 18
  • If both if statements don't match their conditions then this code causes an undefined error. – John Aug 16 '16 at 18:46
0

you should try

d.offsetWidth 

instead of

d.style.width
abbood
  • 23,101
  • 16
  • 132
  • 246
-1

The code d.style.width returns the width explicitly specified by css while d.offsetWidth returns the computed width.

Alex Williams
  • 355
  • 1
  • 4