1

I want to style an element based on the text that is written inside of it.

<div class="target-element">
  Cat
</div>

And if I was guessing how the CSS should look:

.target-element[content="Cat"] {
    background-color: red;
}

This doesnt work of course ^^ , which is where the help comes in.

Eric
  • 6,563
  • 5
  • 42
  • 66
Ian Steffy
  • 1,234
  • 3
  • 18
  • 45

2 Answers2

2

You can set a data-* attribute to the div and catch that to change the css as

div[data-color="red"] {
    color: red;
}
<div class="target-element" data-color="red">
  Cat
</div>
Eric
  • 6,563
  • 5
  • 42
  • 66
Tushar Gupta
  • 15,504
  • 1
  • 29
  • 47
  • The element should change its color to red based on the word 'Cat'. Without 'Cat', the text is simply black. – Ian Steffy Oct 27 '15 at 08:59
2

As far as I know there is no way to do this only with .

If you can use and I would take a look at this example: https://www.codeproject.com/Questions/469131/jIn-hear-we-have-a-single-class-But-I-want-colour

var content = $(".target-element").text();
if (content == "Cat") {
    content.css("background", "red");
}
Eric
  • 6,563
  • 5
  • 42
  • 66