Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struggling with classList.add and getElementsByClassName [duplicate]

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?

like image 543
aproskam Avatar asked Jun 14 '14 12:06

aproskam


People also ask

How do you add multiple classes to a classList?

To add multiple classes to an element, select the element and pass multiple classes to the classList. add() method, e.g. box. classList. add('bg-blue', 'text-white') .

What does the element classList toggle () method do?

toggle() The toggle() button is used for toggling classes to the element. It means adding a new class or removing the existing classes.

How does classList toggle work?

toggle() will add the CSS class if it does not exist in the classList array and return true . If the CSS class exists, the method will remove the class and return false . The classList. toggle() method supports adding and removing CSS classes whether they exist or not in your array with shorter lines of code.

Does IE11 support classList?

classList are not fully supported in IE11, Safari or Opera Mini.


1 Answers

.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.

like image 174
James Hill Avatar answered Sep 21 '22 19:09

James Hill