Skip to content
Advertisement

Javascript onclick script is changing the class on an element not containing specified class

I have a small piece of javascript to add a css class to a button element that already contains two classes under the top level of a menu when clicking outside that menu.

I understood that writing the two classes as below should select only elements that have both classes. It does what has been asked on the element I specify, BUT, it’s also changing the css class of buttons at a lower level.

Here is my code (EDITED as the top line was in my draft but not showing here:)

JavaScript

It’s adding the ‘not-clicked’ class to lower (child) level buttons with the css class 'btn-level-2 clicked' as well.

Also, having added the ‘not-clicked’ class it does not remove the ‘clicked’ class.

No jQuery, please. I’m using vanilla JS only.

Thank you.

UPDATE: It works, so please add your answer so I can accept it! Many thanks.

Advertisement

Answer

Change your class selector to querySelectorAll.

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