Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve the display property of a DOM element?

Tags:

<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.

like image 280
Jichao Avatar asked Sep 23 '10 12:09

Jichao


People also ask

How do you display elements in DOM?

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.

How do you find the value of the DOM element?

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.

How do you display properties in HTML?

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.


2 Answers

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.

like image 173
Quentin Avatar answered Oct 22 '22 09:10

Quentin


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);
}
like image 42
Tim Down Avatar answered Oct 22 '22 10:10

Tim Down