Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery :has(.something:contains()) unsupported?

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.

like image 836
Vegard Larsen Avatar asked Sep 03 '09 11:09

Vegard Larsen


3 Answers

Check this out:

$(document).ready(function(){
    $('span.foo:contains(relevant)').parents('li').each(function() {
       alert($(this).text());
    });
});
like image 52
karim79 Avatar answered Sep 21 '22 06:09

karim79


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

ul li:has(span[class='foo']:contains('relevant'))
like image 41
daddywoodland Avatar answered Sep 21 '22 06:09

daddywoodland


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

like image 37
Kobi Avatar answered Sep 24 '22 06:09

Kobi