Nicros
Nicros

Reputation: 5183

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?

Upvotes: 18

Views: 20719

Answers (3)

javi
javi

Reputation: 11

what about using HAS

$(".parent:has(h2:contains('Statistics'))")

Upvotes: 1

rahul maindargi
rahul maindargi

Reputation: 5655

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

Working http://jsfiddle.net/SayjQ/

Upvotes: 3

Joe
Joe

Reputation: 15538

Use:

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

This uses the :contains() selector.

Upvotes: 23

Related Questions