2

I put this on the head section

var d = parseInt(document.getElementById('test').style.width);
alert(d);

But the output is NaN.

how do you get the value?

Ben
  • 54,723
  • 49
  • 178
  • 224
oYes
  • 73
  • 2
  • 9
  • 2
    You said you put that in the HEAD section? are you executing that code after the document has loaded? try to put that code on the bottom of your body tag, just before – Jose Faeti Jun 24 '11 at 07:06
  • Not related to your question as such, but calling `parseInt()` without specifying the radix in the (optional) second parameter means you may be in for a surprise if parsing a user-input value (or any other value that may have leading zeros). I find it easiest to just always include it, e.g. `parseInt(someValue,10)`. – nnnnnn Jun 24 '11 at 07:16

4 Answers4

0

UPDATED

Reading your question, it seems that you are executing the code in your head section before the DOM has loaded, try to put your script in the bottom of your page, just before </body>.


document.getElementById('test').clientWidth;
document.getElementById('test').offsetWidth;
Jose Faeti
  • 12,126
  • 5
  • 38
  • 52
0

UDPATED

I think the problem is that you've put the code in the <head> of your document, which means it's looking for the test element right away. Unfortunately, the test element hasn't been created yet, because your browser is still parsing the <head>.

So, make sure that code is placed after the test element, and use either .offsetWidth or .clientWidth, and it should work fine.

Ben
  • 54,723
  • 49
  • 178
  • 224
  • That means you don't have an ID attribute on your target element. Add `id='test'` to the element you are trying to get the width of. – Ben Jun 24 '11 at 06:55
  • If the ID is on the body tag, you may need to use `.clientWidth`. – Ben Jun 24 '11 at 07:01
  • Well, you're on the right track, it's probably just a tiny little something...are the upper/lower case correct in document.getElementById? Can you fetch a different element? Try changing the `.style.background='red'` for the `test` element to see if it's being found. – Ben Jun 24 '11 at 07:02
0

style.width will most probably only get the inline style, you have three options:

You can use .clientWidth , .offsetWidth or you can add a inline-style.

See my example : http://jsfiddle.net/WaSKP/2/

Marc Uberstein
  • 12,501
  • 3
  • 44
  • 72
0

Just use,

window.onload=function(){
    alert(document.getElementById("test").clientWidth)
}

That should do the trick.

oYes
  • 73
  • 2
  • 9