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");

2
  • 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. Commented Aug 13, 2018 at 16:11
  • see...stackoverflow.com/questions/3808808/… Commented Aug 13, 2018 at 16:11

2 Answers 2

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'))
Sign up to request clarification or add additional context in comments.

3 Comments

Please don't ignore the question..... Is it not possible to get elements by class name and add a new class?
? I don't get your point, he asks if he can get the elements by class name, So ... I guess my answer is correct
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.
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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.