简体   繁体   中英

how to use style.display value in condition

I'm trying to make a simple accordion. I'm using style.display to check if the display attribute of an element is block or none but it returns no value

var mybtn = document.querySelectorAll("button");

for (var i = 0; i < mybtn.length; i++) {
  mybtn[i].onclick = function() {
    var mySibling = this.nextElementSibling;

    console.log(this.style.display);

    if (mySibling.style.display == "block") {
      mySibling.style.display = "none";
    } else {
      mySibling.style.display = "block";
    }
  }
}

 var mybtn = document.getElementById("click_me"); mybtn.onclick = function() { var mySibling = this.nextElementSibling; //console.log(this.style.display); if (mySibling.style.display === "none") { mySibling.style.display = "block"; } else { mySibling.style.display = "none"; } } 
  <button type="button" id="click_me">Click Me!</button> <button type="button">Show/Hide</button> 

The reason why your code is not working as you expected, is because you are using type–converting == comparison instead of the strict comparison === operator. This means that in your case you are checking whether display is a truthy value, which both none and block are (or pretty much any display value other than an empty string). This causes mySibling.style.display to always to be set display: none . More about the difference in comparison operators you can read here

If you use a strict comparison operator instead your code will work as expected, see the following code snippet:

 var mybtn = document.querySelectorAll("button"); for (var i = 0; i < mybtn.length; i++) { mybtn[i].onclick = function() { var mySibling = this.nextElementSibling; console.log(this.style.display); if (mySibling.style.display === "none") { mySibling.style.display = "block"; } else { mySibling.style.display = "none"; } } } 
 <button>Show/Hide</button> <span>Hello im the sibling</span> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM