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.
5 Answers
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>
2 Comments
You can match attribute values though. If you use custom data attributes, it might get what you want.
3 Comments
td[data-carrier="Verizon"] { color: #F00; } Results in td cells with the data-carrier attribute of value Verizon giving them the color of Red.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
:contains selector didn't made it into the later specifications.@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
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.