开发者

document.getElementById(...).style.display is blank [duplicate]

This question already has answers here: How to 开发者_StackOverflow中文版retrieve the display property of a DOM element? (4 answers) Closed 6 years ago.
function test( id )
{
    alert( document.getElementById( id ).style.display );
}

What exactly does getElementById.style.display return? Is it an object, or a value? The alert shows nothing at all. I'm not using pure numbers for the id and it is unique.


DOM methods like document.getElementById() create objects which point to- and contains certain details about- a specified HTMLElement or set of elements.

Unfortunately the .style property only knows about the style properties set using that same feature. In the example below, clicking what color? will not work until you have clicked change color.

<html>
<head>
<script>
function whatColor() {
    var d = document.getElementById( 'ddd' );
    alert( d.style.backgroundColor );
}
function changeColor() {
    var d = document.getElementById( 'ddd' );
    d.style.backgroundColor='orange';
}
</script>
<style>
#ddd {
    background-color:gray;
}
</style>
</head>
<body>
<input type="button" onclick="whatColor();" value="what color?" />
<input type="button" onclick="changeColor();" value="change color" />
<div id="ddd">&nbsp;</div>
</body>
</html>

I recommend reading PKK's great page on getComputedStyle and currentStyle (IE, of course is different) http://www.quirksmode.org/dom/getstyles.html

At the end of the tutorial, there is a very decent function for your purposes, although frameworks such as jQuery do provide very convenient & powerful functions for styling page elements: http://api.jquery.com/css/


it displays the value that was dynamically set. if you want to find the current value you need the computed value. the same question was asked, check my answer here

Stackoverflow


Actually it is possible using window.getComputedStyle(element[, pseudoElt]).

The method gives the values of all the CSS properties of an element after applying the active stylesheets and resolving any basic computation those values may contain.


Your snippet will only show a value for style.display if it has actually been set, it will not necessarily show default values.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜