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.
Asked
Active
Viewed 8.2k times
5 Answers
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
-
2I 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
-
2This 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
-
1This 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
-
11Interesting, but it's only for static media "This selector is for static media only (i.e., print and not screen display)." – Joel Nov 22 '09 at 01:01
-
1ah yes i didn't catch that nuance .. i can see why it makes sense however (maybe) . thanks for spotting that – Scott Evernden Nov 22 '09 at 01:19
-
4
-
-
3
-
-
this works if i edit the css in devtools and add it,but @screen it is ignored – JoSSte Apr 25 '22 at 15:29
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
-
I don't think accessing a nodeList via bracket notation is standard. – Carcigenicate Mar 12 '16 at 20:38