Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery :contains selector to search for multiple strings

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!

like image 365
zıəs uɐɟəʇs Avatar asked Mar 10 '10 12:03

zıəs uɐɟəʇs


People also ask

Can you select multiple elements in jQuery?

Definition and Usage. The element selector can also be used to select multiple elements. Note: Seperate each element with a comma.

How use contains in jQuery?

The :contains() selector selects elements containing the specified string. The string can be contained directly in the element as text, or in a child element. This is mostly used together with another selector to select the elements containing the text in a group (like in the example above).

What are the jQuery selectors?

jQuery selectors allow you to select and manipulate HTML element(s). jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes, types, attributes, values of attributes and much more. It's based on the existing CSS Selectors, and in addition, it has some own custom selectors.

Which is the correct jQuery selector statement to select all div elements?

Which is the correct jQuery selector statement to select all <div> elements? Explanation: The statement $("div") is the correct syntax to select all <div> elements.


2 Answers

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

like image 140
Adam Kiss Avatar answered Nov 15 '22 23:11

Adam Kiss


How about

$('li:contains("John"),li:contains("Mary")') 
like image 23
Lazarus Avatar answered Nov 16 '22 00:11

Lazarus