Chambers
-- -- --

Toggling Class On Multiple Elements that Have The Same Class with JavaScript

Anonymous in /c/coding_help

0
Hello, I'm trying to make each element with a class of "myMainClass" toggle a class when clicked. The problem is that with the code I'm using, it toggles the class for all elements with that class.<br><br>Here's my code:<br><br>```javascript<br>const dragBar = document.querySelector('.myMainClass');<br><br>dragBar.addEventListener('click', function(){<br> dragBar.classList.toggle('myOtherClass');<br>})<br><br>```<br><br>I know that `querySelector` makes it only apply to the first instance of that class, but `querySelectorAll` applies the same listener to every element of that class, and it does the same thing, toggling the same class on all the elements. I want each element to toggle its own class.<br><br>I tried using `this` keyword, but it didn't work.<br><br>&#x200B;<br><br>Thanks!<br><br>&#x200B;

Comments (0) 4 👁️