4

I have the following style defined for an element with ID #foo.

#foo {
    display: none;
}

I run the following JavaScript code:

var foo = document.getElementById('foo')
alert('[' + foo.style.display + ']')

I was expecting the output to be [none]. However, the output is simply []. Here is a demo: http://jsfiddle.net/bEmUE/

Why is foo.style.display an empty string here?

What can I write in the code to figure the actual display property of this element?

Lone Learner
  • 18,088
  • 20
  • 102
  • 200

1 Answers1

11

The style attribute only gives you information about inline styles.

However, it is not useful for learning about the element's style in general, since it represents only the CSS declarations set in the element's inline style attribute, not those that come from style rules elsewhere, such as style rules in the section, or external style sheets.

Source: MDN HTMLElement.style

Instead you should use this:

getComputedStyle(foo).display;

demo

Brigand
  • 84,529
  • 20
  • 165
  • 173
  • It seems like 'innerText' (used in your example) is not cross browser compatible: http://stackoverflow.com/questions/1359469/innertext-works-in-ie-but-not-in-firefox – Whistletoe Aug 03 '13 at 19:59
  • Thanks, I updated the fiddle to use jQuery (wasn't relevant to the question, just for demo purposes). – Brigand Aug 03 '13 at 20:01
  • @Whistletoe - His demo uses innertext to only demonstrate a solution to what the OP has asked and is in no way part of the solution! So thanks for the heads up, but it's irrelevant! – bPratik Aug 03 '13 at 20:01
  • Yeah, i was just mystified why the fiddle didn't work for me. – Whistletoe Aug 03 '13 at 20:02