12

I am trying to receive the original CSS width value of an object using JavaScript. However, if I use:

var originalWidth = document.getElementById(<idOfObject>).style.width;

It always returns blank. I've also noticed that any property I access using this syntax will return blank. I know for sure that the given element exists, since

alert(document.getElementById(<idOfObject>));

does shows me the right object.

Can anyone help me to solve this problem?

5 Answers 5

13

You probably try to get the value which was set in stylesheet, not directly like this:

document.getElementById(<idOfObject>).style.width = '100px';

If you want to get the width of the element you can use innerWidth property:

var width = document.getElementById(<idOfObject>).offsetWidth;
3
  • innerWidth or offsetWidth? Besides I'll add that you can access inline style properties, like here: <div style="width: 100px;">...</div> Jun 3, 2011 at 18:06
  • I just figured it out myself, you were right! Thanks for the answer!
    – Tiddo
    Jun 3, 2011 at 18:08
  • None of them, the correct is clientWidth; offsetWidth returns the width plus border width. innerWidth may return nothing if the property width is set by external css or even style setction
    – drodsou
    Jul 26, 2012 at 17:16
12

None of the previous answers were right.

The property you are looking for is clientWidth, but not in "style"

document.getElementById('idOfObject').clientWidth;

That will work both on "width" set with external css, style seccion or even inline style="width:80px"

General note: don't use <div width="500"> as it has no effect

The mentioned offsetWidth is the second best choice, but it does not return the exact width set in css, but that width plus border width

Other options like innerWidth that works with window object didn't work for me on divs.

This bizarre issue of realizing style.width not working properly, wasted 2 hours of my precious time :-), hope this answer shorts that time for anyone else in the future.

1
<div  style="width:10%" id="mydiv" >

OR

<div  style="width:10px" id="mydiv" >

var mydiv = document.getElementById("mydiv");
 var curr_width = mydiv.style.width;
alert(curr_width);

This works for me

1

I tried it and I can get the value

http://jsfiddle.net/xyd95/

Well, unless the width has no unit

http://jsfiddle.net/xyd95/1/

1
  • the difference was that I'd set the value in an external stylesheet. As bjornd said, the object.style.width can only show the inline DOM property of the object.
    – Tiddo
    Jun 3, 2011 at 18:09
0

I believe this will work

function getWidth()
{

x = document.getElementById(<idOfObject>)
return x.offsetWidth;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.