'Conditional if statement with CSS [duplicate]
Is there any way to configure a conditional with CSS?
What I'm trying to configure is, having a single class, if the text on that class change so I can define different colors to the text. For example, if "div class:´test´" have assigned the text "Disabled" I want to apply red color to the text, but if the text for the same class is "Enabled" want to assign green color to the text.
Is there any way to achieve that with only one class?
Solution 1:[1]
The closest solution to the one you propose with css is using attribute selectors, an example below
p[data-text="Enabled"]{
color: blue;
}
p[data-text="Disabled"]{
color: red;
}
<p data-text="Enabled">Enabled</p>
<p data-text="Disabled">Disabled</p>
But with javascript you can get a solution like the following:
let elemento= document.querySelectorAll(".case")
elemento.forEach(e => e.setAttribute( "data-text",e.textContent ) )
.case[data-text="Enabled"]{
color:red;
}
<p class="case">Enabled</p>
<p class="case">Disabled</p>
Update: improvement recommended by user @connexo
let elemento= document.querySelectorAll(".case")
elemento.forEach(e => e.dataset.text= e.textContent )
.case[data-text="Enabled"]{
color:red;
}
<p class="case">Enabled</p>
<p class="case">Disabled</p>
Solution 2:[2]
Adding to the solution suggested by Usiel, you can also use CSS to display the text in the data-attributes:
[data-text]::before { content: attr(data-text); }
[data-text="Enabled"]{
color: blue;
}
[data-text="Disabled"]{
color: red;
}
<p data-text="Enabled"></p>
<p data-text="Disabled"></p>
Solution 3:[3]
I think you could achieved this with Javascript.
document.getElementById(id).style.property = new style as shown in JavaScript HTML DOM - Changing CSS
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | connexo |
| Solution 3 | jimmymcheung |
