Vanilla JavaScript adding classes to elements [duplicate]

ⅰ亾dé卋堺 提交于 2021-01-29 11:08:56

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!