wkm wkm - 1 year ago 100
jQuery Question

jQuery :contains - exclude matching text in descendants

jQuery :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.




Answer Source


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

jsFiddle example

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download