user4876127
user4876127

Reputation: 31

how to replace class name dynamically in javascript

I want to change a class dynamically and append a counter to the end of it. I wrote this code but it is treated like strings.

This is the code:

var divClass = document.getElementById('div2');
var i = 1;
setInterval(function () {
  divClass.className=divClass.className.replace('color','color'+ i);
  i++;
},5000);

how can i fix this issue?

Upvotes: 1

Views: 3255

Answers (3)

Get Off My Lawn
Get Off My Lawn

Reputation: 36309

You could use the classList feature that is in JavaScript like this:

var divClass = document.getElementById('div2');
var i = 1;
setInterval(function () {
    divClass.classList.remove('color' + (i - 1));
    divClass.classList.add('color' + i++);
}, 5000);

Your numbers are more than likely getting treated as a string because you are concatenating with a string. By placing items within parentheses, they will be executed as numbers (because anything in parentheses get run first) then concatenated as a string.

Upvotes: 1

nottu
nottu

Reputation: 379

I think the issue is that after the first loop the class name will be color1 and your replacing only the "color" part so you end up with color12 You could just set className since that overrides the previous one

divClass.className = 'color'+ i;

if you had classes before you can store them and them first so you don't override them : var classes = divClass.className; and when you set them divClass.className = classes + ', color'+ i;

Upvotes: 1

Jasiu
Jasiu

Reputation: 17

Use instead:

element.className = 'other const clases' + 'color'+ i;

You have to change full string of class or change it in 2 steps with for example regex and then assign it again.

Upvotes: 0

Related Questions