根据原始类名追加类

时间:2014-11-21 17:08:28

标签: javascript html css

无论如何使用JavaScript为页面上的某个类添加一个额外的类。

例如:

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

但是我想操纵它,所以它添加了一个类(带有一个计数器到底)

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

1 个答案:

答案 0 :(得分:5)

(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>

修改

我已将代码包装在自调用匿名函数中,以防止全局存在var elements