Struggling with classList.add and getElementsByClassName [duplicate]
Asked Answered
B

3

10

I'm trying to add a extra class to some elements with a specific class(input-fieldset).

<fieldset id="pay" class="input-fieldset"></fieldset>
<fieldset id="address" class="input-fieldset"></fieldset>

So I did some searches and found this:

var element = document.getElementsByClassName('input-fieldset');
element.classList.add(' input-fieldset-awesome');

I'm trying to add the class input-fieldset-awesome.

But it doesn't work, I get the error:

Uncaught TypeError: Cannot read property 'add' of undefined(anonymous function)

What am I doing wrong?

Bhatt answered 14/6, 2014 at 12:1 Comment(1)
You are getting an array of elements from getElementsByClassName, try targeting only a particular elementDivertissement
F
17

.getElementsByClassName() returns an HTMLCollection (array of objects) that must be iterated.

The code below will accomplish what you're after.

// Get desired elements
var element = document.getElementsByClassName('input-fieldset');

// Iterate through the retrieved elements and add the necessary class names.
for(var i = 0; i < element.length; i++)
{
    element[i].classList.add('input-fieldset-awesome');
    console.log(element[i].className);
}

Here's a working fiddle to play with.

Fetter answered 14/6, 2014 at 12:10 Comment(6)
classList, (compatibility).Are
Classlist is a cleaner. better and relatively new way to add classes to elements. It doesn't involve manipulating the className stringDivertissement
Thanks for the heads up guys. I modified my code to reflect your comments.Fetter
Thank you very much, I'v been looking for it all day, finally you gave me the working codeDive
Is it the same code to remove class?Dive
@Khalil, yes, of course.Fetter
S
2

document.getElementsByClassName returns an array-like object of all child elements which have all of the given class names.

In your case you should modify your code like this.

var element = document.getElementsByClassName('input-fieldset')[0];
element.classList.add(' input-fieldset-awesome');

or

var elements = document.getElementsByClassName('input-fieldset');
for (var i = 0; i<elements.length; i++) {
   elements[i].classList.add('input-fieldset-awesome');
}
Soiree answered 14/6, 2014 at 12:12 Comment(0)
J
1

getElementsByClassName returns a HTMLCollection which doesn't have classList property, you should iterate through the collection.

[].slice.call(document.getElementsByClassName('input-fieldset'))
  .forEach(function(elem) {
      elem.classList.add('cls');
  });
Johnsonjohnsonese answered 14/6, 2014 at 12:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.