Given the HTML below, I am trying to use jQuery to match all the list items that have a span with the class "foo" and that span should contain the text "relevant".
<ul>
<li>Some text <span class="foo">relevant</span></li>
<li>Some more text <span class="foo">not</span> <span class="bar">relevant</span></li>
<li>Even more <span class="foo">not so either</span></li>
<li>Blablabla <span class="foo">relevant</span> <span class="bar">blabla</span></li>
<li>No foo here <span class="bar">relevant</span></li>
</ul>
Note that there are also a few span's with the class "bar", and that also has the text "relevant", that should not be included.
My attempts at a selector:
ul li:has(.foo:contains('relevant"))
This does not work. The next example selects something, but does not take into account that there are multiple span's inside the list:
ul li:has(span:contains('relevant"))
Here is a live example that you can play with. In a working version, only the first and fourth elements of that list should be selected.
Check this out:
$(document).ready(function(){
$('span.foo:contains(relevant)').parents('li').each(function() {
alert($(this).text());
});
});
Beaten to it... But if you want a pure selector you were darn close
ul li:has(span[class='foo']:contains('relevant'))
I tried to reverse the order of the selectors:
$("ul li:has(:contains('relevant').foo)").css('background-color', 'red');
This seems to work well, can't say why though: http://jsbin.com/asoma
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With