Jichao Jichao - 5 months ago 25
Javascript Question

How to retrieve the display property of a DOM element?

<html>
<style type="text/css">
a {
display: none;
}
</style>
<body>
<p id="p"> a paragraph </p>
<a href="http://www.google.com" id="a">google</a>
</body>
<script type="text/javascript">
var a = (document.getElementById('a')).style;
alert(a.display);
var p = (document.getElementById('p')).style;
alert(p.display);
p.display = 'none';
alert(p.display);
</script>
</html>


The first and the second
alert
display nothing other than a empty string, which I thought should be
none
and
block
.
However after the intensionally
display
setting, the third
alert
finally alert
none
.

But Why? How could I retrieve the
display
property correctly?

Thanks.

Answer

The .style.* properties map directly onto the style attribute, not to the applied style. For that you want getComputedStyle.

I'd give serious consideration to toggling .className and separating the presentation from the logic entirely.