43

I would like to apply a different style to all anchors containing a specific word. Can it be done in pure CSS? It's ok if it's CSS3-only.

Nakilon
  • 34,866
  • 14
  • 107
  • 142
Tamás Szelei
  • 23,169
  • 18
  • 105
  • 180

5 Answers5

39

No. :contains was once proposed but is not in the current Working Draft of CSS3 Selectors.

You would need some JavaScript, for example:

for (var i= document.links.length; i-->0;)
    if (/\bSpecificWord\b/i.test(document.links[i].innerHTML)
        document.links[i].style.color= 'red';
bobince
  • 528,062
  • 107
  • 651
  • 834
  • 2
    I really hope they have fixed this issue by now. It seemings glaringly obvious that styling an element by the words in its contents is an extremely common problem. – Ian Steffy Oct 27 '15 at 08:28
21

You can match attribute values though. If you use custom data attributes, it might get what you want.

Divya Manian
  • 1,927
  • 11
  • 16
  • 2
    This answer works just fine in chrome. `td[data-carrier="Verizon"] { color: #F00; }` Results in `td` cells with the `data-carrier` attribute of value `Verizon` giving them the color of `Red`. – Mark Tomlin Aug 24 '15 at 04:40
  • 1
    This would be the same as creating a separate CSS class name for each content value, ex. '.carrier-verizon {color:red}' – ed22 Mar 06 '20 at 07:14
6

yes there is a :contains selector in CSS3.

li:contains("special"){text-style: italic;}

it is mentioned about 1/2 down this page here

This is something you can also do with jQuery too ...

Scott Evernden
  • 39,136
  • 15
  • 78
  • 84
3

@bobince help me and I wrote this code:

var x = document.getElementsByTagName('TD');
for (var i= x.length; i-->0;)
    if (x[i].innerHTML=='closed')
        x[i].parentNode.style.background= '#FEE';

If the content of some TD is 'closed' then the background color of the TR will be identified with light red color.

lynx_74
  • 1,633
  • 18
  • 12
-3

Use the Hitch which is a tiny JS library. You can easily apply content based style to any element. It has lots of options and great for conditional styling.

Enes
  • 323
  • 1
  • 4
  • 11