Monday, June 3, 2024
44
rated 0 times [  46] [ 2]  / answers: 1 / hits: 20409  / 10 Years ago, sat, june 14, 2014, 12:00:00

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?


More From » getelementsbyclassname

 Answers
39

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


[#70575] Thursday, June 12, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
trevionbronsonr

Total Points: 160
Total Questions: 85
Total Answers: 110

Location: Bonaire
Member since Wed, Mar 29, 2023
1 Year ago
trevionbronsonr questions
;