简体   繁体   中英

Javascript OnClick function for multiple Div Class elements that reveal a block of text when clicked on

I am trying to enable an Onclick event to fire up when any of my div elements that match the div class "Clicker" is clicked on. However iI am not so good with JavaScript and do not know how to go about this. I was successful when I used the "document.getElementById" when my divs were made into Id and not "Class" elements but only one could function. see my code below;

 document.getElementsByClassName("Clicker").addEventListener("click", function () { var infoBox = document.getElementsByClassName("thumbnail-reveal-txt"); if (infoBox.style.display == "none") { infoBox.style.display = "block"; } else { infoBox.style.display = "none"; } })
 <div class="thumbnail-reveal-txt" style="position: absolute; display: none;"> <div class="thumbnail-reveal-txt" style="position: absolute; display: none;"> <div class="thumbnail-reveal-txt" style="position: absolute; display: none;">

You can use querySelector and querySelectorAll

 document.querySelector(".Clicker").addEventListener("click", function () { const infoBox = document.querySelectorAll(".thumbnail-reveal-txt"); infoBox.forEach(i => { if (i.style.display == "none") { i.style.display = "block"; } else { i.style.display = "none"; } }) })
 <button class="Clicker">click</button> <div class="thumbnail-reveal-txt" style="position: absolute; display: none;">1</div> <div class="thumbnail-reveal-txt" style="position: absolute; display: none;">2</div> <div class="thumbnail-reveal-txt" style="position: absolute; display: none;">3</div>

When you use getElementsByClassName, you're not specifying wich of the elements you are trying to change the className property.

For that, you can use a loop

document.getElementsByClassName("Clicker").addEventListener("click", function () {
  var infoBox = document.getElementsByClassName("thumbnail-reveal-txt");

for (let i = 0; i < infoBox.length; i +=1) {

if (infoBox[i].style.display == "none") {
    infoBox[i].style.display = "block";
  } else {
    infoBox[i].style.display = "none";
  }

}
 


})

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