48

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.

0

5 Answers 5

43

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

You would need some JavaScript, for example:

Array.from(document.links).forEach(link => {
  if (/\bSpecificWord\b/i.test(link.innerHTML)) {
    link.style.color = 'red';
  }
});
<a href="#">SpecificWord</a>
<a href="#">OtherWords</a>

Sign up to request clarification or add additional context in comments.

2 Comments

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.
Works perfectly, I just use it on my Tampermonkey script.
25

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

3 Comments

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.
This would be the same as creating a separate CSS class name for each content value, ex. '.carrier-verizon {color:red}'
This is an interesting answer (checking attribute value), but it seems not related to the question (checking attribute content). Maybe we can add additional context about why it's better to try to don't answer the original problem (spoiler: because it's not possible).
7

Yes, there is a :contains selector in CSS3, but is for static media only. For example, just print and not screen display. Usage:

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

It is mentioned about 1/2 down in xml.com about CSS3 selectors

As additional compatibility layer, there is the jQuery :contains selector too ...

4 Comments

The :contains selector didn't made it into the later specifications.
Does not work on Chrome.
Doesn't work on Firefox v55.x
this works if i edit the css in devtools and add it,but @screen it is ignored
3

@bobince help me and I wrote this code:

var tableCells = document.getElementsByTagName('TD');
for (var index = tableCells.length; index-- > 0;)
    if (tableCells[index].innerHTML == 'closed')
        tableCells[index].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.

1 Comment

I don't think accessing a nodeList via bracket notation is standard.
-4

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.

1 Comment

Hitch is a dead link, has it moved?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.