简体   繁体   中英

How can I toggle a class to various items?

I just want to toggle a class from various items. I mean, I have 5 divs with .item class inside a div with .container class. Can I toggle a new class to those 5 .items? Maybe with a loop?

I was trying to do it but it seems that the loop goes infinite.

This is what I tried:

<div class="container">
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <button onclick="myFunction()"></button>
</div>

<script>
   function myFunction () {
       var x = document.getElementsByClassName("item");
       for (i=0; i<x.length; i+1) {
           x[i].classList.toggle('new-class');
       }
   }
</script>

I expect something like this at the end (maybe with some loop in JS):

<div class="container">
    <div class="item new-class"></div>
    <div class="item new-class"></div>
    <div class="item new-class"></div>
    <div class="item new-class"></div>
    <div class="item new-class"></div>
</div>

You can do it by using the for loop and the classList.add() method.

function myFunction() {
   var items = document.querySelectorAll('.item');

   for(var i = 0; i < items.length; i++) {
    items[i].classList.add('new-class');
   }
}

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