I have written a function to display or not display the title of an element. My code works correctly. But only the first element reacts to my code and other elements don't react to my code. My codes are as follows:
let eye = document.querySelector(".box_icon");
let excerpt = document.querySelector(".title_box");
eye.addEventListener("click", function() {
if (this.classList.contains("bi-play-circle-fill")) {
this.classList = "bi bi-power box_icon";
excerpt.style.display = "block";
} else {
this.classList = "bi bi-play-circle-fill box_icon";
excerpt.style.display = "none"
}
});
.box_main {
display: flex;
justify-content: space-around;
}
.box_mini {
width: 250px;
height: 200px;
background: #5ec7ff;
box-shadow: 0 0 4px #000;
}
.box_icon {
font-size: 25px;
margin: 10px 40% 6px;
color: #7f7f7f;
}
.title_box {
font-size: 45px;
margin: 25px 15px 20px;
color: #f9ff4d;
display: none;
}
<link href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css" rel="stylesheet" />
<section class="box_main">
<div class="box_mini">
<i class="bi bi-play-circle-fill box_icon"></i>
<h1 class="title_box">Title BOX</h1>
</div>
<div class="box_mini">
<i class="bi bi-play-circle-fill box_icon"></i>
<h1 class="title_box">Title BOX</h1>
</div>
<div class="box_mini">
<i class="bi bi-play-circle-fill box_icon"></i>
<h1 class="title_box">Title BOX</h1>
</div>
<div class="box_mini">
<i class="bi bi-play-circle-fill box_icon"></i>
<h1 class="title_box">Title BOX</h1>
</div>
</section>
Please guide me to edit the java script code I wrote.
querySelectorAll(). The returned elements will be stored in the form of an array. So to add an event listener to all of them, you'll need to loop over them. I.e. use a.forEachor in your case just aforloop, so you can also reference the .excerpt elements that you want to style by their index (i.e.excerpt[i]).