1

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");
El Coo Cooi
  • 13
  • 1
  • 4
  • 4
    What do you mean by "my code breaks"? The reason for that is probably that `getElementsByClassName` returns a list of elements and not a single element. – str Aug 13 '18 at 16:11
  • see...https://stackoverflow.com/questions/3808808/how-to-get-element-by-class-in-javascript – Sean T Aug 13 '18 at 16:11

2 Answers2

3

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'))
Vashnak
  • 352
  • 1
  • 6
  • Please don't ignore the question..... `Is it not possible to get elements by class name and add a new class?` – Mamun Aug 13 '18 at 16:31
  • ? I don't get your point, he asks if he can get the elements by class name, So ... I guess my answer is correct – Vashnak Aug 13 '18 at 19:48
  • Mmhhh, I see. You are right. But, btw I give him a more recent solution than getElementByClassname. Which is (in my opinion) easier to read. – Vashnak Aug 13 '18 at 19:59
0

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>
Mamun
  • 66,969
  • 9
  • 47
  • 59