-1

In below example, i is a variable. We want to make div's background color automatically changes as the i'value changes. How to add variable into class tag in html?

.js

var i = 0;

i will be changed after some processing.

.html

<div class="bgcolor+i"></div>

.css

.bgcolor0{
   backgorund: red
}
.bgcolor1{
   background: green
}
...
lei lei
  • 1,753
  • 4
  • 19
  • 44
  • [You can see an example on this page](https://stackoverflow.com/questions/44734374/how-to-set-a-javascript-variable-in-attribute-of-a-html-tag) –  Aug 01 '22 at 06:15

2 Answers2

-1

You want to add the class name dynamically. Just write the class name in this way

<div class=`bgcolor-${i}`></div>
Zain Ejaz
  • 289
  • 1
  • 9
-1

you can do it in JavaScript - get the element by it's id and set the css class in code. (you need to give that div id for that)

@justinas gave you a link with a sample how to do it - change element class with javascript

Dani
  • 14,639
  • 11
  • 62
  • 110