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.
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.
You need the computed value of the display property for the element. You can get this as follows. Note that most browsers support window.getComputedStyle()
whereas the nearest equivalent in IE is the element's currentStyle
property:
var el = document.getElementById('a');
var styleObj;
if (typeof window.getComputedStyle != "undefined") {
styleObj = window.getComputedStyle(el, null);
} else if (el.currentStyle != "undefined") {
styleObj = el.currentStyle;
}
if (styleObj) {
alert(styleObj.display);
}
I'd recommend using a JavaScript library for getting computed style. For example, using jQuery you can retrieve computed style with the css() method...
$("#a").css("display");
The css() method is a cross-browser solution as it internally uses the style object and both the getComputedStyle method and the currentStyle object.