Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find element where child items h2 text has a specific value

I think this is really simple but I can't seem to find the right selector syntax. I have html like this:

<div class="parent">
    <h2>Summary</h2>
    <p>... bunch of content ...</p>
</div>
<div class="parent">
    <h2>Statistics</h2>
    <p>... bunch of content ...</p>
</div>
<div class="parent">
    <h2>Outcome</h2>
    <p>... bunch of content ...</p>
</div>

I want to find the div whose h2 child contains the text 'Statistics'.

I tried various combinations of:

$(".parent").find("h2[text='Statistics'").parent()

which doesn't work as the find returns an empty set. If I do this:

$(".parent").find("h2").text("Statistics").parent()

I get back 3 elements- all of which appear to be the div containing Statistics. I could add first() to that, but it seems kind of gross. What is the right syntax to find that one item?

like image 526
Nicros Avatar asked May 09 '13 16:05

Nicros


3 Answers

Use:

$(".parent").find("h2:contains('Statistics')").parent();

This uses the :contains() selector.

like image 177
Joe Avatar answered Nov 06 '22 14:11

Joe


$(".parent").find("h2:contains('Statistics')").each(function(){
    var div=$(this).parent();
   // use div as you want
})

Working http://jsfiddle.net/SayjQ/

like image 23
rahul maindargi Avatar answered Nov 06 '22 16:11

rahul maindargi


what about using HAS

$(".parent:has(h2:contains('Statistics'))")
like image 1
javi Avatar answered Nov 06 '22 14:11

javi