There is a code:

....... <div id="modifier-1" class="modifier">........</div> <div id="modifier-2" class="modifier">........</div> <div id="modifier-3" class="modifier">........</div> <div id="modifier-4" class="modifier">........</div> ...... 

And there is a class = "mod-before". Tell me how you can add this class to all these IDs using JS

    2 answers 2

    Select all elements whose id attribute starts with modifier is selected using ^= .

    As a result, it has a selection of the form: div[id^="modifier"]

     // JavaScript var divs = document.querySelectorAll('div[id^="modifier"]'); var i = divs.length while(i--) { divs[i].classList.add('mod-before'); } console.log(divs[0], divs[1]); 
     <div id="modifier-1" class="modifier">........</div> <div id="modifier-2" class="modifier">........</div> <div id="modifier-3" class="modifier">........</div> <div id="modifier-4" class="modifier">........</div> 

    • Thank you, the question has been resolved, this is exactly what the div [id ^ = "modifier"] needed - Andrew

    select all divs with the modifier class, for example using the document.querySelectorAll function

    Run through the selected divs in a loop and add the required class to each one, for example, using the classList.add function

    • The fact is that the class '' modiier '' is used in other places of the code, and you only need to add the class "mod-before" with this ID - Andrey
    • @ Andrei, this is how? well, the easiest way to use another class for the right divs is to choose it - Grundy