Error reading element styles when set in stylesheet - is this abrowser bug?

C

Ciaran

Consider this:
<html>
<head>
<style type="text/css">
p.ex1 {margin-left:50px;}
</style>
</head>
<body onload="
alert(document.getElementById('ex1').style.marginLeft);
alert(document.getElementById('ex2').style.marginLeft); ">

<p class="ex1" id='ex1'>A paragraph with a 20px left margin.</p>
<p id='ex2' style='margin-left:20px;'>A paragraph with a 20px left
margin.</p>

</body>
</html>

Why is the first alert empty and how can I fix it without adding the
style inline?

Thanks,
Ciarán
 
D

David Mark

Consider this:
<html>
<head>
<style type="text/css">
p.ex1 {margin-left:50px;}
</style>
</head>
<body onload="
alert(document.getElementById('ex1').style.marginLeft);
alert(document.getElementById('ex2').style.marginLeft);  ">

<p class="ex1" id='ex1'>A paragraph with a 20px left margin.</p>
<p id='ex2' style='margin-left:20px;'>A paragraph with a 20px left
margin.</p>

</body>
</html>

Why is the first alert empty and how can I fix it without adding the
style inline?

It's empty because there is no inline style set for that element.

Google for getComputedStyle (standard) and currentStyle (IE < 9 pseudo-
equivalent). That method and property can be used to retrieve the
value you are after (but only by coincidence as you used pixel units).

Alternatively, assuming the rules are not declared as !important, you
could set the inline margin-left style to "0px" and see how much the
offsetLeft property changes.
 
C

Ciaran

It's empty because there is no inline style set for that element.

Google for getComputedStyle (standard) and currentStyle (IE < 9 pseudo-
equivalent).  That method and property can be used to retrieve the
value you are after (but only by coincidence as you used pixel units).

Alternatively, assuming the rules are not declared as !important, you
could set the inline margin-left style to "0px" and see how much the
offsetLeft property changes.



Hey Thanks a lot David, this worked like a charm:
window.getComputedStyle(document.getElementById('ex1'),null).getPropertyValue("margin-
left")
Ciarán
 
R

Ry Nohryb

(...)
window.getComputedStyle(document.getElementById('ex1'),null).getPropertyVal ue("margin-
left")

And you can drop the window. in there, because the properties of the
window object are global:

getComputedStyle(document.getElementById('ex1'),null).getPropertyValue("margin-
left")
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top