I have a class called .box-159
where the number changes every time the screen is refreshed. Is there a way to define this field (say background-color
) in the CSS?
In this article, we will see how to dynamically create a CSS class and apply to the element dynamically using JavaScript. To do that, first we create a class and assign it to HTML elements on which we want to apply CSS property. We can use className and classList property in JavaScript.
color = "red"; you can apply the style change dynamically. Below is a function that turns an element's colour to red when you pass it the element's id . You could also use setAttribute(key, value) to set a style on an element. For example, you could set the colour of an element to red by calling element.
You can use Javascript for adding a class: setAttribute and className both method are used to set class (class attribute), these method are not used to adding another class with existing one. simply using className= will clear te other classes.
HTML elements can be assigned multiple classes by listing the classes in the class attribute, with a blank space to separate them.
Yes it is possible just by using CSS only.
^="class"
which select all elements whose class is prefixed by "box-"[class^="box-"] {
background: red;
height: 100px;
width: 100px;
margin: 10px 0;
display:block
}
<div class="box-159"></div>
<span class="box-147"></span>
<article class="box-76878"></article>
*="class"
(equivalent to CSS attribute selector) which select all elements whose class contains at least one substring "box-".[class*="box-"] {
background: red;
height: 100px;
width: 100px;
margin: 10px 0;
display:block
}
<div class="box-159"></div>
<span class="box-147"></span>
<article class="box-76878"></article>
You can add an additional class, like so, then both those elements will have the class' CSS attributes:
.box-class {
background-color: red;
width: 100px;
height: 100px;
margin-bottom: 20px;
}
<div class="box-class box-4"></div>
<div class="box-class box-159"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With