Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Only show the FAQ answer related to the clicked question

I want only display one answer when I click on a question, but all answers are being shown.

let ques = document.querySelectorAll(".question")
let ans = document.querySelectorAll(".answer")

ques.forEach((question) => {
  question.addEventListener("click", () => {
    ans.forEach((answer) => {
      answer.classList.toggle("display")
    })
  })
})
.answer {
  display: none;
}

.answer.display {
  display: block;
}
<div class="faq">
  <div class="question">question</div>
  <div class="answer">answer</div>
</div>
<div class="faq">
  <div class="question">question</div>
  <div class="answer">answer</div>
</div>
<div class="faq">
  <div class="question">question</div>
  <div class="answer">answer</div>
</div>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The issue in your code is because you’re looping through all the .answer elements, not the one related to the clicked .question.

To do what you need you can use closest() and querySelector() to find the .answer within the same parent as the .question which was clicked and toggle the display class on it. You can then loop through all other .answer elements and remove the display class from them.

Here’s a working example:

const questions = document.querySelectorAll(".question");
const answers = document.querySelectorAll(".answer");

questions.forEach(q => {
  q.addEventListener("click", () => {
    const answer = q.closest('.faq').querySelector('.answer');
    answer.classList.toggle('display');  
    answers.forEach(a => a != answer && a.classList.remove("display"))
  })
})
.answer {
  display: none;
}

.answer.display {
  display: block;
}
<div class="faq">
  <div class="question">question</div>
  <div class="answer">answer</div>
</div>
<div class="faq">
  <div class="question">question</div>
  <div class="answer">answer</div>
</div>
<div class="faq">
  <div class="question">question</div>
  <div class="answer">answer</div>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading