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:)

document.getElementById("myId").addEventListener("click", addClass);
function addClass(event) {
// the click is triggered outside the menu
    if(event.target.type != 'button') {
// these are top level buttons only
    var buttons = document.getElementsByClassName('btn-level-1 clicked');
        for (var i = 0; i < buttons.length; i++) {
        buttons[i].classList.add('not-clicked');
        buttons[i].classList.remove('clicked'); }
    }
}

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.

document.getElementById("myId").addEventListener("click", addClass);
function addClass(event) {
    if(event.target.type != 'button') {
    var buttons = document.querySelectorAll('.btn-level-1.clicked');
        for (var i = 0; i < buttons.length; i++) {
        buttons[i].classList.add('not-clicked');
        buttons[i].classList.remove('clicked'); }
    }
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement