wkm wkm - 2 months ago 11
jQuery Question

jQuery :contains - exclude matching text in descendants

jQuery :contains() selector

http://api.jquery.com/contains-selector/


The matching text can appear directly within the selected element, in
any of that element's descendants, or a combination thereof.


How can I omit elements that have matching text in any of that element's descendants. I only want to get elements where the matching text appears directly within the selected element.

In the example below I only want spans that contain the word "Red" to have red coloured text.

<span>Green
<span>Red</span>
</span>
<span>Red</span>

jQuery("span:contains('Red')").css("color","red");


http://jsfiddle.net/UNydR/2/

Answer

Try:

jQuery("span:contains('Red')").filter(function () {
    return ($(this).text() == 'Red')
}).css("color", "red");

jsFiddle example

Comments