Home > Mobile >  How to Add a click Event Listener to nested class element
How to Add a click Event Listener to nested class element

Time:09-28

I'm trying to add a click event listener to all the "question classes" nested deep inside the container class. I can't seem to figure out the issue here.

let colorChange = document.querySelectorAll(".container .dropdowns .dropdown-function .question")
  for(i = 0; i < colorChange.length; i  ){
    colorChange.addEventListener("click", function(){
      colorChange[i].classList.add("change-color");
    });
}
.change-color{
  color: green
}
<div class = "container">
  <main class = "dropdowns">
    <h1 class = "title">FAQ</h1>
    <div class = "dropdown-function">
      <h2 class = "question"> Question 1 </h2>
      <p class = "dropdown-content"> Answer 1 </p>
    </div>
    <div class = "dropdown-function">
       <h2 class = "question"> Question 2 </h2>
       <p class = "dropdown-content"> Answer 2 </p>
    </div>
  </main>
</div>

CodePudding user response:

First, I will suggest you to notice if there is any error in console.

You are trying to attach the event (click) to the NodeList, not an individual element. Also declare the variable using let to create a block scope for the variable:

let colorChange = document.querySelectorAll(".container .dropdowns .dropdown-function .question")
  for(let i = 0; i < colorChange.length; i  ){
    colorChange[i].addEventListener("click", function(){
      colorChange[i].classList.add("change-color");
    });
}
.change-color{
  color: green
}
<div class = "container">
  <main class = "dropdowns">
    <h1 class = "title">FAQ</h1>
    <div class = "dropdown-function">
      <h2 class = "question"> Question 1 </h2>
      <p class = "dropdown-content"> Answer 1 </p>
    </div>
    <div class = "dropdown-function">
       <h2 class = "question"> Question 2 </h2>
       <p class = "dropdown-content"> Answer 2 </p>
    </div>
  </main>
</div>

  • Related