<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 display property also allows the author to show or hide an element. It is similar to the visibility property. However, if you set display:none , it hides the entire element, while visibility:hidden means that the contents of the element will be invisible, but the element stays in its original position and size.
HTML DOM getAttribute() method is used to get the value of the attribute of the element. By specifying the name of the attribute, it can get the value of that element. To get the values from non-standard attributes, we can use the getAttribute() method.
The display property specifies the display behavior (the type of rendering box) of an element. In HTML, the default display property value is taken from the HTML specifications or from the browser/user default style sheet. The default value in XML is inline, including SVG elements.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With