Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

js style properties returns blank

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?

like image 216
Tiddo Avatar asked Jun 03 '11 17:06

Tiddo


3 Answers

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;
like image 196
bjornd Avatar answered Nov 08 '22 23:11

bjornd


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.

like image 12
drodsou Avatar answered Nov 08 '22 23:11

drodsou


<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

like image 1
zod Avatar answered Nov 08 '22 22:11

zod