问题
I would like to use pure JS to add classes to some elements and am familiar with selecting the element with an ID, but when I've tried to use getElementsByClassName, my code breaks. Is it not possible to get elements by class name and add a new class?
I know the following code works, but, again, would like to target the element by className.
document.getElementById("id-name").classList.add("new-class");
回答1:
you can use querySelectorAll to select every element containing your class, and then, add your new class on all of them :
document.querySelectorAll('.class-name')
.forEach(element => element.classList.add('new-class'))
回答2:
Is it not possible to get elements by class name and add a new class?
It is of course possible. Document.getElementsByClassName() returns an array-like object of all child elements which have all of the given class names. You have to iterate them to add the class:
Using forEach()
:
[...document.getElementsByClassName("myClass")].forEach(function(el){
el.classList.add("new-class");
});
.new-class{
color: red;
}
<div class="myClass">Test</div>
<div class="myClass">Test 2</div>
<div class="myClass">Test 3</div>
Using for
loop:
var elList = document.getElementsByClassName("myClass");
for(var i=0; i < elList.length; i++){
elList[i].classList.add("new-class");
}
.new-class{
color: red;
}
<div class="myClass">Test</div>
<div class="myClass">Test 2</div>
<div class="myClass">Test 3</div>
来源:https://stackoverflow.com/questions/51826516/vanilla-javascript-adding-classes-to-elements