0

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>

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.