0

I need to check the displaystyle 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.

Marcos Pérez Gude
  • 21,869
  • 4
  • 38
  • 69
Christoph Frings
  • 427
  • 4
  • 14

2 Answers2

0
<p id="dispa">display</p>
<div id="mydiva" style="display:none;">
    sample div a
</div>
<p id="dispb">display</p>
<div id="mydivb">
    sample div b
</div>




<script>
$(document).ready(function(){
    $("#b").click(function(){
        $("#mydiva").toggle();
        $("#mydivb").toggle();
    });
});
</script>

Is this what you trying to do?

0

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>
Pete
  • 57,112
  • 28
  • 117
  • 166