240

Is there a way to select an element in css based on element text?

ie:

li[text=*foo]

<li>foo</li>
<li>bar</li>

That probably doesn't work.

Edit: Also only need to support Chrome.

Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
Harry
  • 52,711
  • 71
  • 177
  • 261

3 Answers3

141

I know it's not exactly what you are looking for, but maybe it'll help you.

You can try use a jQuery selector :contains(), add a class and then do a normal style for a class.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Błażej Klisz
  • 1,730
  • 2
  • 16
  • 16
  • 10
    This worked for me. Ended up using something like: `$("div:contains('Text')") .closest("div.parent_div") .css("background", "#555");` – JoshP May 20 '15 at 14:12
  • 39
    @dineshygv No it should not be marked as the answer. The question asked for a CSS Selector. This answer is a jQuery selector which is entirely different and adds the dependency of using jQuery. Proper CSS Selectors do not require any special library, only conformance to CSS & DOM standards by the browser. – uchuugaka Apr 05 '17 at 03:07
  • 2
    Unbelievably, this works in Rails unit tests `assert_select '.text-muted:contains("Total Raised")', 'Total Raised'`. http://guides.rubyonrails.org/v5.0/testing.html#testing-views I did not expect it to because I thought the unit tests use Ruby CSS selectors, not JQuery. – Chloe Dec 26 '17 at 04:38
93

Not with CSS directly, you could set CSS properties via JavaScript based on the internal contents but in the end you would still need to be operating in the definitions of CSS.

zellio
  • 31,308
  • 1
  • 42
  • 61
14

It was probably discussed, but as of CSS3 there is nothing like what you need (see also "Is there a CSS selector for elements containing certain text?"). You will have to use additional markup, like this:

<li><span class="foo">some text</span></li>
<li>some other text</li>

Then refer to it the usual way:

li > span.foo {...}
Community
  • 1
  • 1
Agos
  • 18,542
  • 11
  • 56
  • 70
  • 23
    This can be confusing. The selector being described is going off of the class on the element, not the text inside of it. Yes, it says "You will have to use additional markup", but with a cursory glance, that could easily be missed. – krillgar Mar 09 '16 at 20:11