Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DOM element's style property is an empty string when accessed using JavaScript [duplicate]

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?

like image 570
Lone Learner Avatar asked Dec 21 '22 02:12

Lone Learner


1 Answers

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

like image 174
Brigand Avatar answered Apr 30 '23 03:04

Brigand