views:

2482

answers:

3

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!

+5  A: 

How about

$('li:contains("John"),li:contains("Mary")')
Lazarus
And jQuery doesn't even index anything twice. So there's an automatic filter and Lazarus' answer really finds four elements.
Paul
Thanks, that is what i was hoping would work, but it doesn't. This selector doesn't return any results. I made a quick try with:$('li:contains("John")','li:contains("Mary")').text() and all i got back was "". Even $('li:contains("John")','li:contains("Mary")').css('font-color','red') didn't seem to work.
Stefan
I think your are inserting a `'` in between the two `li:contains`.
rahul
BTW: i am using jQuery 1.4.1
Stefan
So, even correcting the bogus syntax i had in my tests mentioned above, this will still select all the <li> elements. $('li:contains("John"),li:contains("Mary")').css('color','red')And this (single quotes separating the selectors): $('li:contains("John")','li:contains("Mary")').css('color','red') doesn't select anything at all.
Stefan
Ah... I see what you mean, you only want LI that has *both* pieces of text... hmmmm... I'll need to think about that.
Lazarus
Oh gosh, this cold really affected my brain. Of course it works like Lazarus says, but i didn't make my question very clear.I wanted to select only <li> elements, which contain both strings, "John" and "Mary". Is that possible at all?BTW: this was my first post to stackoverflow and i must say, it works extremely well and blindingly fast.Thanks so much!
Stefan
Exactly Lazarus. Sorry for being a so vague in my Q. Blame it on my cold.
Stefan
Adam Kiss
@Stefan Stack Overflow is your friend :)
Mark Schultheiss
@Adam Kiss, nice one.
Lazarus
A: 

In JQuery, you can separate selectors (along with custom selectors) by a comman ,:

$('selector1, selector2, selector3, and_so_on...')
Sarfraz
+7  A: 

answer

I think it's more something like:

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

explanation

Just think of :contains just as it wass .someClass:

$('li.classone, li.classtwo'). //you want either classone OR classtwo
$('li.classone.classtwo'). //you want BOTH on one element
/* same with :contains */
$('li:contains("mary"), li:contains("john")'). // either one OR two
$('li:contains("mary"):li:contains("john")'). //li, which contains both

snippet

proof:

http://jsbin.com/ejuzi/edit

Adam Kiss