T
T
techday2021-06-06 13:50:00
JavaScript
techday, 2021-06-06 13:50:00

How to change class on click?

On click, the active class is hung on one element, but if you click on the second element, it is hung there too, and remains on the first one.
What should be added so that the active class is only in one place? When you click on the second element, it was removed from the first, and the second was added and vice versa.

let menuArrows = document.querySelectorAll('.menu__arrow');
  if (menuArrows.length > 0) {
    for (let index = 0; index < menuArrows.length; index++) {
      const menuArrow = menuArrows[index];
      menuArrow.addEventListener("click", function (e) {
        menuArrow.parentElement.classList.toggle('_active');
      });
    }
  }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Egor Kharlamov, 2021-06-06
@techday

Good day.
I gave you a solution to the problem - https://codesandbox.io/s/unruffled-dew-4viji
In short:
1) Define the elements that we can click
on 2) Create a function on click. In it, we are looking for an element that is already active, and if we find it, we delete the class of the active element. Then it remains to assign the class of the active element to the one that was clicked.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question