Christoph Frings Christoph Frings - 4 months ago 7
CSS Question

Incorrect 'display' style attribute

I need to check the

display
style attribute for a given
div
. In the document below, both divs'
display
attribute is set through css (one to
none
, the other to
block
) and later through javascript when the button is clicked, but
div.style.display
is empty as long as it has not been set by script (hence I need two clicks on the buttons to get the correct values).



function myFunction() {
document.getElementById("dispa").innerHTML = document.getElementById("mydiva").style.display;
document.getElementById("mydiva").style.display = "none";
document.getElementById("dispb").innerHTML = document.getElementById("mydivb").style.display;
document.getElementById("mydivb").style.display = "none";
}

#mydiva {
display:block;
}
#mydivb {
display:none;
}

<button onclick="myFunction()" id="b">See</button>
<p id="dispa">display</p>
<div id="mydiva">
sample div a
</div>
<p id="dispb">display</p>
<div id="mydivb">
sample div b
</div>





Note: in my project, reading of
display
is to happen in
window.onload
, not through button press, but results are the same.

Answer

You can get the display style using the function below

function myFunction() {
  document.getElementById("dispa").innerHTML = getDisplayStyle("mydiva");
  document.getElementById("mydiva").style.display = "none";
  document.getElementById("dispb").innerHTML = getDisplayStyle("mydivb");
  document.getElementById("mydivb").style.display = "none";
}

function getDisplayStyle(elementId) {
  var element = document.getElementById(elementId)
  return element.currentStyle ? element.currentStyle.display :
    getComputedStyle(element, null).display;
}
#mydiva {
  display: block;
}
#mydivb {
  display: none;
}
<button onclick="myFunction()" id="b">See</button>
<p id="dispa">display</p>
<div id="mydiva">
  sample div a
</div>
<p id="dispb">display</p>
<div id="mydivb">
  sample div b
</div>

Comments