1

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?

1
  • 1) What is treated as a string? 2) What is the end state you would like your class name to look like? Commented Nov 22, 2016 at 21:26

3 Answers 3

1

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;

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

Comments

1

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.