views:

643

answers:

5

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.

+5  A: 

Check this out:

$(document).ready(function(){
    $('span.foo:contains(relevant)').parents('li').each(function() {
       alert($(this).text());
    });
});
karim79
That selects the span.foo, not the list item.
Vegard Larsen
@Vegard Larsen - sorry about that, edited.
karim79
+1  A: 

I know this may not be as elegant, but at least it'll work:

$("ul li .foo:contains('relevant')").parent("li");

I couldn't get your version to work either...

peirix
+2  A: 

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

Kobi
+3  A: 

Beaten to it... But if you want a pure selector you were darn close

ul li:has(span[class='foo']:contains('relevant'))
daddywoodland
A: 

Not sure why you're having that problem with the selector, confirmed this does work though:

$("ul li").filter(":has(span.foo:contains('relevant'))").css('background-color', 'green');
gnarf