Element.style.display is not what is displayed in the browser.

Perhaps a duplicate question, but cannot find the answer.

element.style.display is not what is displayed in the browser.

Instead of returning the actual value (e.g. block or inline, etc.), it returns empty. Tested on Chrome 56.0.2924.87 (64-bit).

How to get the actual displayed value?

function displayStyle(aEvent) { aEvent.target.textContent=aEvent.target.style.display; } window.onload = function() { var top_array = document.getElementsByClassName("top"); for(var i = 0; i < top_array.length; i++) { top_array[i].addEventListener("click", displayStyle, false); } } 
 .top{ background-color:#FFF8DC; } 
 <div class="top">top (click it and it will disappear because its style.display is empty)</div> 
+5
source share
2 answers

CSS styles are not available for JavaScript unless they were previously set in JavaScript or they were hardcoded as inline styles.

Use getComputedStyle () :

 function displayStyle(aEvent) { var target = aEvent.target; target.textContent = window.getComputedStyle(target).getPropertyValue('display'); } window.onload = function() { var top_array = document.getElementsByClassName("top"); for (var i = 0; i < top_array.length; i++) { top_array[i].addEventListener("click", displayStyle, false); } } 
 .top { background-color: #FFF8DC; } 
 <div class="top">top (click it and it will now show "block" since we're getting its computed style.)</div> 
+8
source

It works if you set it directly in the style attribute:

 function displayStyle(aEvent) { aEvent.target.textContent=aEvent.target.style.display; } window.onload = function() { var top_array = document.getElementsByClassName("top"); for(var i = 0; i < top_array.length; i++) { top_array[i].addEventListener("click", displayStyle, false); } } 
 .top{ background-color:#FFF8DC; } 
 <div class="top" style="display: block;">top (click it and it will disappear because its style.display is empty)</div> 

Announcement: setting it to CSS also does not work.

I still don't know why, anyway.

Now I know, thanks to Rick Hitchcock's answer .

+1
source

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


All Articles