0

Is there anyway with JavaScript to add an additional class to every element that has a certain class on the page.

So for example:

<div class="but-class">Button</div> 

but I want to manipulate this so it adds a class (with a counter to the end)

<div class="but-class custom-class1"></div> 

1 Answer 1

5

(function() { var elements; //store the collection of matching elements elements = document.querySelectorAll(".but-class"); // loop through the collection appending your new class for (var i = 0; i < elements.length; ++i) { elements[i].classList.add('custom-class'+i); // append the value of 'i' to your class name } }());
.custom-class0 { color: green; } .custom-class1 { color: red; } .custom-class2 { color: blue; } .custom-class3 { color: purple; }
<div class="but-class">Button</div> <div class="but-class">Button</div> <div class="but-class">Button</div> <div class="but-class">Button</div>

EDIT

I've wrapped the code in a self invoking anonymous function to prevent var elements existing globally.

Sign up to request clarification or add additional context in comments.

4 Comments

To make that work, you'll need to alter: elements[i].classList.add('custom-class1'); to: elements[i].classList.add('custom-class'+i);
Also, .classList doesn't enjoy complete cross-browser compatibility, notably in IE8 and 9. Might want to fall back to: elements[i].className = elements[i].className + " custom-class" + i;
I missed the part about the counter
@uʍopǝpısdn: (upsidedown dropping my display)the counter part was introduced after the edit, I was wondering where it came from too. +1 Michael for pointing that out anyway :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.