I am not able to toggle my active class on my sidebarItem

hi guys https://www.codeply.com/p/KusoWECAgN this is my code about a sidebar. (please ignore the styling as it is problem of this online editor i’m using). here i want on clicking each sidebar item with class sidebar-item to change active class to clickactive at line 1134 in css , but it is not changing. Can someone please look into my code especially in my javascript code to find the error and help removing it.

You can’t add an event listener to a NodeList. You have to loop it like you are doing inside toggleActiveClass. BTW, forEach works on a NodeList in modern browsers, so you do not need to convert it to an array unless if you want to support browsers that do not have support for forEach on NodeLists.

sideItem.forEach(item => {
  item.addEventListener('click', toggleActiveClass);
})

Secondly, you are toggling the clickactive class on all the elements, not just the one that was clicked, which doesn’t seem like something you would want to do.

Edit: You might want to look into event delegation

https://javascript.info/event-delegation

i did that but it is adding active class to all the sidebar item


i want that when i click on a sidebar item active class appears on it and gets off it when i click on any other . How can i do that?

That was the second point I made. Look at the links I gave.

You have to identify the click target and only toggle the class on the target that is clicked.


Example code
const sideItem = document.querySelectorAll('.sidebar-item');

//writing toggle function
function toggleActiveClass(event) {
    const target = event.target
    
    if (target.matches('.sidebar-item')) {
        event.target.classList.toggle('clickactive');
    }
}

sideItem.forEach(item => {
    item.addEventListener('click', toggleActiveClass);
})

Another issue you will see is when you click the icon inside the sidebar-item it will not toggle the class. One option is to disable pointer-events on the icons.

.sidebar-item-icon {
  pointer-events: none;
}

hi first of all thank you for helping me .
but my problem still persists after trying your code. I’m able to get my active class on a sidebar item but that class is not getting removed from that item when i’m clicking any other item
secondly, you tell me why you told me
.sidebar-item-icon { pointer-events: none; }
what benefit it gives

I know it doesn’t. That was not part of the requirements you initially posted. Try to figure that one out on your own. You can ask for help if you need it.

pointer-events: values

none

The element is never the target of pointer events; however, pointer events may target its descendant elements if those descendants have pointer-events set to some other value. In these circumstances, pointer events will trigger event listeners on this parent element as appropriate on their way to/from the descendant during the event capture/bubble phases.