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

Chris Morgan
  • 86,207
  • 24
  • 208
  • 215
ShrimpCrackers
  • 4,388
  • 17
  • 50
  • 76

4 Answers4

6

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/

Mike Figueroa
  • 236
  • 1
  • 2
  • Thanks for making it clear the .style only knows about the ones it set. I think the jquery thing was what I was looking for. – ShrimpCrackers Jul 14 '11 at 06:05
1

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.

D. Fiore
  • 11
  • 2
1

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

Community
  • 1
  • 1
Ibu
  • 42,752
  • 13
  • 76
  • 103
  • If a style is given in an external stylesheet, does that not override the default value? I've defined display in an external CSS sheet for the element I'm passing in, but it shows as undefined. – ShrimpCrackers Jul 14 '11 at 05:53
  • what i mean by that is, it will read the a property that is set with javascsript. to get the value set from the stylesheet, you need the computed value – Ibu Jul 14 '11 at 06:40
0

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

blankabout
  • 2,597
  • 2
  • 18
  • 29