Home > database >  How to add a class to a group of elements in an array
How to add a class to a group of elements in an array

Time:09-13

I want to add the class ".mlft" to a specifics elements in an array

    const divSubMenu = document.querySelectorAll('.accordion-collapse'); // 209 elements have the array
    let divSubmenuarray = divSubMenu [0, 166, 187, 205, 208]; // i need to add the class for these specific elements 
for (j = 0; j < divSubmenuarray.length; i  ){
    function addMargin(){
        divSubmenuarray.classList.add('mlft')
    }
    addMargin();
    console.log(divSubmenuarray);
}

CodePudding user response:

You have invalid syntax. Put the indexes to access in an array and loop over that instead.

const divSubMenu = document.querySelectorAll('.accordion-collapse');
for (const i of [0, 166, 187, 205, 208]) {
    divSubMenu[i].classList.add('mlft');
}
  • Related