Grabbing style.display property via JS only works when setting inline?

I am trying to capture the DISPLAY div property on a page. I can only seem to capture it if it was set via the built-in style attribute.

If my JS is this:

alert(document.getElementById('myDiv').style.display); 

It will warn the “block” using this HTML:

 <div id="myDiv" style="display: block;"></div> 

However, if I installed it through an external stylesheet:

 #myID {display: block} 

and my HTML:

 <div id="myDiv"></div> 

then my warning is an empty string.

Why is this?

+4
source share
1 answer

This is a "feature" of CSS. To actually get the style, you need to use window.getComputedStyle (most browsers) or element.currentStyle (Internet Explorer).

A fix for implementing window.getComputedStyle IE can be found at: http://snipplr.com/view/13523/getcomputedstyle-for-ie/ . Also, see this page for more information: http://www.quirksmode.org/dom/getstyles.html#link7 (there is a script below for a cross-browser alternative to getComputedStyle).

This should work in all browsers (based on the function from the QuirksMode link above):

 var elem = document.getElementById("myDiv"); if (elem.currentStyle) { var displayStyle = elem.currentStyle.display; } else if (window.getComputedStyle) { var displayStyle = window.getComputedStyle(elem, null).getPropertyValue("display"); } alert(displayStyle); 
+9
source

Source: https://habr.com/ru/post/1340861/


All Articles