JavaScript Help: FAQ Project

Hi Guys! I am a beginner and therefore learning by working on projects. This is a FAQ project which I am struggling with.

There are questions and answers and I have divided them into categories. If I choose first category - “all” - all questions displays or when I click on the other category, only questions related to this category display and others gets hidden.

Similarly, when I click on a question, it’s respective answer should display or hide as I toggle. This is what I meant to achieve.

Now, when the page loads and I click on the questions, their respective answers hides and displays (toggle) - works fine as I expected. Note: It only works when I refresh the page.

But my problem is as I click on the categories including “all” , functionality of show and hide questions disappears. It does not work with any category.

In other words, I click on a category and then click on a question to check the answer, toggling does not work at all.

As again, I refresh the page functionality works as desired. Here is the Code Pen link to my code…

Please help me find solutions for these two questions:

  1. What and where am I doing wrong?
  2. How to solve it?

Thank you!

So, at a quick glance, it seems you’re attaching the click listener to the question element itself, through you’re adding and removing them based on user input.

If they Don’t exist, or if they get created after the listener was created, they don’t inherit that listener. You can only attach listeners to existing elements.

The solution might be Event Delegation. If the nearest static (or a fixed, existing settlement) container of those question elements were to listen for a click, it can tell you which element was clicked.

Google "event delegation javascript, to learn more - i would, but on my phone and working.