Opinionated Programmer - Jo Liss's musings on enlightened software development.

CSS: Selecting text nodes (as with XPath’s text())

In case anyone else is looking for this:

Given HTML like this, …


… in XPath you can select the <div> element with //div[text()="bananas"].

Question: Is there a CSS equivalent?

Answer: No, it’s not possible to do the same with CSS. CSS selectors only work on elements, not on the text nodes they contain. There used to be a :contains() pseudo-class for this in a CSS 3 draft, but it’s gone.

So if you feel you need to match text, you’ll have to use XPath instead (or put more classes and ids on your elements, so you can match against those).

If you’re using jQuery, you’re lucky though: It has a custom :contains() selector.