Skip to content
Advertisement

Add/Remove CSS Class with JS Loop

I have a navigation menu that displays a group of notes from the clicked topic. The note can either have class note if it is visible or class invisible if it is hidden. I want only the notes from the topic clicked to show.

The problem is that some notes from other topics are also being shown. Even though the length of thisTopic is always 2.

I am new to JavaScript so maybe there is an error in my loop? Thanks in advance 🙂

JavaScript
JavaScript
JavaScript

Advertisement

Answer

There are two issues with your code:

  • You’re removing the note class from elements.
  • You’re not giving elements that should be hidden by default the invisible class.

JavaScript
JavaScript
JavaScript

With that in mind however, I’d strongly recommend a few things:

  • Reverse your logic. (Hide by default, then activate.)
  • Use the id attribute at a higher level instead of class for topic#.

Reverse Your Logic

Currently, you have 3 topics with 2 notes each. Imagine instead, that you have 5 topics with 5 notes each. With your current logic, you’ll need to assign the invisible class, by default to 20 section elements. Instead, use an active class and you’ll only need to assign it to 5 section elements:

JavaScript

You can see how this impacts your snippet below when taken to a larger scale:

JavaScript
JavaScript
JavaScript

Use id and grouping

It’s common practice to group elements within a parent element. In your case, I recommend encapsulating your section elements into a div that is designed for each topic using the id attribute:

JavaScript

Use Bootstrap

If using third party tools like Bootstrap aren’t out of the question, they already handle this and provide very easy to follow code for doing so, taking the leg work off of you:

JavaScript
JavaScript

Best of luck!

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement