Append a class to an existing selected class (selected class statement has multiple classes selected) in Javascript

I’m selecting multiple classes with one statement:

 var sidebarList = document.getElementsByClassName("side-nav nav-links nav-item");

I’m trying to add a class called open to it:

sidebarList.classList.add("open");

But I am getting this error Cannot read property 'add' of undefined and I do not understand why.

This is the jquery equivalent of what I’m trying to do

var sidebarList = $(".side-nav ul li");
sidebarList.addClass("open");

1 thought on “Append a class to an existing selected class (selected class statement has multiple classes selected) in Javascript”

  1. You have to use querySelectorAll for selecting elements with multiple classnames as selector. After that you’ve to loop through your selected elements and add the class to each element.

    var sidebarList = document.querySelectorAll(".side-nav.nav-links.nav-item");
    
    sidebarList.forEach(function(oItem){ 
      oItem.classList.add("open");
      console.log("Added class 'open' to list item");
    });
    <ul>
    <li class="side-nav nav-links nav-item" >Test</li>
    <li class="side-nav nav-links nav-item" >Test</li>
    <li class="side-nav nav-links nav-item" >Test</li>
    </ul>
    Reply

Leave a Comment