简体   繁体   中英

Adding a class to all elements within a for loop

I'm having a for loop to get a certain task done.Now in that for loop,in the last iteration, I need to add the green-color class to all the elements which has the class checkMarks .

This is my code, currently it adds the green-color class only to the first element. Is there a way to do this without having to use another for loop inside the current for loop?

const studentLength = 24;
for(let i=0; i<studentLength; i++){
   //something happens here

   if(i===studentLength ){ //if last iteration 
       document.querySelectorAll(".checkMarks").classList.add("green-color");
   }
}

You need to iterate the result of querySelectorAll and apply the class to each element:

 document.querySelectorAll(".checkMarks").forEach(e => e.classList.add("green-color"));
 .green-color { color: green; }
 <div class="checkMarks">TEST</div> <div class="checkMarks">TEST2</div> <div class="checkMarks">TEST3</div> <div class="checkMarks">TEST4</div> <div class="checkMarks">TEST5</div> <div class="checkMarks">TEST6</div> <div class="checkMarks">TEST7</div>

You need to loop since the All in querySelectorAll returns a nodelist, but you should use forEach on the students too I wrap in a spread [...] to handle early EDGE browsers

students.forEach(student => { /*something happens here */});
[...document.querySelectorAll(".checkMarks")].forEach(chk => chk.classList.add("green-color"));

If there is only ONE checkMark you can do document.querySelector(".checkMarks").classList.add("green-color") without the all , but vanilla JS does not support adding to a list in one go like the equivalent jQuery $(".checkMarks").addClass("green-color") would

Personally, I would use a for...of loop (ES6):

 const divs = document.querySelectorAll(".checkMarks"); for (const div of divs) { div.classList.add("green-color"); }
 .green-color { color: green; }
 <div class="checkMarks">DIV1</div> <div class="checkMarks">DIV2</div> <div class="checkMarks">DIV3</div> <div class="checkMarks">DIV4</div> <div class="checkMarks">DIV5</div> <div class="checkMarks">DIV6</div> <div class="checkMarks">DIV7</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM