jQuery :contains selector to search for multiple strings

zıəs uɐɟəʇs picture zıəs uɐɟəʇs · Mar 10, 2010 · Viewed 58.3k times · Source

Assuming i have:

<li id="1">Mary</li>
<li id="2">John, Mary, Dave</li>
<li id="3">John, Dave, Mary</li>
<li id="4">John</li>

If i need to find all <li> Elements which contain "John" and "Mary", how would i construct the jQuery?

A search for a single string seems easy:

$('li:contains("John")').text()

I am looking for something like the following pseudo code:

$('li:contains("John")' && 'li:contains("Mary")').text()

Thanks!

Answer

Adam Kiss picture Adam Kiss · Mar 10, 2010

Answer

To find li's that have text containing BOTH Mary AND John:

$('li:contains("Mary"):contains("John")')

To find li's that have text containing EITHER Mary OR John:

$('li:contains("Mary"), li:contains("John")')

Explanation

Just think of the :contains as if it was a class declaration, like .class:

$('li.one.two').      // Find <li>'s with classes of BOTH one AND two
$('li.one, li.two').  // Find <li>'s with a class of EITHER one OR two

It's the same with :contains:

$('li:contains("Mary"):contains("John")').      // Both Mary AND John
$('li:contains("Mary"), li:contains("John")').  // Either Mary OR John

Demo

http://jsbin.com/ejuzi/edit