0

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?

maumotec
  • 1
  • 1
  • 1
    Welcome to Stack Overflow! No, CSS is content unaware. You cannot style an element with CSS only based on the text within the element. – disinfor May 05 '22 at 22:17
  • Thank you so much for your welcome. Sorry for the delay on my response, I got covid, but I'm better now. Gotcha, thank you so much, I'm pretty new to all this world but studying constantly now. – maumotec May 10 '22 at 20:23

3 Answers3

2

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>
Usiel
  • 671
  • 3
  • 14
0

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>
connexo
  • 53,704
  • 14
  • 91
  • 128
-1

I think you could achieved this with Javascript. document.getElementById(id).style.property = new style as shown in JavaScript HTML DOM - Changing CSS