Skip to content Skip to sidebar Skip to footer

Vanilla Javascript Adding Classes To Elements

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

Solution 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'))

Solution 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;
}
<divclass="myClass">Test</div><divclass="myClass">Test 2</div><divclass="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;
}
<divclass="myClass">Test</div><divclass="myClass">Test 2</div><divclass="myClass">Test 3</div>

Post a Comment for "Vanilla Javascript Adding Classes To Elements"