Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Probably a duplicate question but can not find the answer.

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

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

How do I get the actual rendered 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>
like image 417
J.Joe Avatar asked Mar 30 '17 17:03

J.Joe


2 Answers

CSS styles are not available to JavaScript unless they have been formerly set in JavaScript or they have been hardcoded as inline styles.

Use getComputedStyle() instead:

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>
like image 195
Rick Hitchcock Avatar answered Oct 18 '22 00:10

Rick Hitchcock


Works if you set it directly in 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>

Obs.: setting it on CSS also doesn't work.

I still don't know why, anyway.

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

like image 29
Dinei Avatar answered Oct 17 '22 23:10

Dinei