Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does element.style.display is blank if display declared on CSS [duplicate]

Tags:

javascript

css

Why does this JS return blank if the style is declared in CSS, and works good when declared inline?

//html
<img id="myImg" src="http://jsfiddle.net/favicon.png" />
<img id="myImg2" src="http://jsfiddle.net/favicon.png" style="display:none;" />

/css
#myImg {
    display:none;
}

//vanilla JS
var el = document.getElementById('myImg');
var el2 = document.getElementById('myImg2');
console.log(el.style.display); // blank
console.log(el2.style.display); // 'none' - as expected

Fiddle here

like image 822
Rikard Avatar asked Jul 29 '13 11:07

Rikard


1 Answers

The style property maps onto the HTML style attribute, not the cascaded or computed style.

Use getComputedStyle if you want to get that.

like image 166
Quentin Avatar answered Oct 03 '22 18:10

Quentin