AnonymousJan 09, 2024
Here's an example to illustrate how CSS Variables can be used to generate attribute selectors dynamically:
HTML:
<div data-category="coding">Javascript</div>
<div data-category="coding">React Js</div>
<div data-category="technology">Iphone</div>
<div data-category="technology">Mac Book</div>
CSS:
:root {
--category: "coding";
}
div[data-category="var(--category)"] {
color: purple;
}
Consequently, the first two elements will be matched by the CSS rule since they have a data-category
attribute with the value "coding". These elements' text colour will be set to purple.
If you want to dynamically change the value of --category
, you can do so with JavaScript by modifying the CSS Variable value. For example:
document.documentElement.style.setProperty('--category', 'coding');