Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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.

like image 353
ShrimpCrackers Avatar asked Jul 14 '11 04:07

ShrimpCrackers


People also ask

Why does document getElementById show null?

getelementbyid(...) is null would seem to indicate that there is no such element with an ID passed to getElementById() exist. This can happen if the JavaScript code is executed before the page is fully loaded, so its not able to find the element.

How do I display a document in getElementById?

To show an element, set the style display property to “block”. document. getElementById("element").

Can you use getElementById twice?

You can use the getElementById() method as many times as you wish, there's no quota assigned to that method.


3 Answers

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/

like image 62
Mike Figueroa Avatar answered Oct 16 '22 21:10

Mike Figueroa


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

like image 40
Ibu Avatar answered Oct 16 '22 20:10

Ibu


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.

like image 26
D. Fiore Avatar answered Oct 16 '22 20:10

D. Fiore