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>
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With