问题描述:

Is there anyway with JavaScript to add an additional class to every element that has a certain class on the page.

So for example:

<div class="but-class">Button</div>

but I want to manipulate this so it adds a class (with a counter to the end)

<div class="but-class custom-class1"></div>

网友答案:

(function() {
    var elements;
    //store the collection of matching elements
    elements = document.querySelectorAll(".but-class");
    // loop through the collection appending your new class
    for (var i = 0; i < elements.length; ++i) { 
       elements[i].classList.add('custom-class'+i); // append the value of 'i' to your class name
    }
}());
.custom-class0 {
    color: green;
}
.custom-class1 {
    color: red;
}
.custom-class2 {
    color: blue;
}
.custom-class3 {
    color: purple;
}
<div class="but-class">Button</div>
<div class="but-class">Button</div>
<div class="but-class">Button</div>
<div class="but-class">Button</div>
相关阅读:
Top