AliRıza Adıyahşi
AliRıza Adıyahşi

Reputation: 15866

JavaScript .style.display?

I want to get display attribute from an HTML element. When I write inline CSS, it works, but if I use a class it doesn't.

This works:

<p id="p1" style="display:none;">This is some text.</p>​
<script>alert(document.getElementById("p1").style.display);</script>

http://jsfiddle.net/bwzAN/2/

This does not work:

<style>.deneme{ display: none; }​</style>
<p id="p1" class="deneme">This is some text.</p>​
<script>alert(document.getElementById("p1").style.display);</script>

http://jsfiddle.net/bwzAN/7/

Why? Is it possible to make the second case behave like the first? How can I fix it?

Upvotes: 3

Views: 5839

Answers (3)

Jamesking56
Jamesking56

Reputation: 3901

You need to get the "Computed Style" (i.e. the 'End Result') rather than your setup.

I've created a JSFiddle (A fork of your non-working original) to help you: http://jsfiddle.net/Jamesking56/qTKYK/2/

Upvotes: 1

devnull69
devnull69

Reputation: 16564

Take a look at getComputedStyle()/getPropertyValue(). The property .style.display will only return the inline style property as you already mentioned.

var yourDisplay = window.getComputedStyle(document.getElementById('yourID'), null).getPropertyValue('display');

Upvotes: 1

Zoltan Toth
Zoltan Toth

Reputation: 47677

Try it with getComputedStyle() - DEMO

$(document).ready(function(){
    var elem = document.getElementById("p1");
    var st   = window.getComputedStyle(elem, null).getPropertyValue("display");

    alert( st );
});

Upvotes: 6

Related Questions