17

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?

Nicros
  • 5,031
  • 12
  • 57
  • 101

3 Answers3

23

Use:

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

This uses the :contains() selector.

Joe
  • 15,205
  • 8
  • 49
  • 56
  • this actually doesnt qualify as a correct answer. it will work in some cases, but the question was "Find element where child items h2 text has a specific value". this code will also find h2 elements which contain the text. the text can be in the beginning, the middle, the end or the entirety. so it doesnt find an element which its text has a specific value. – Heriberto Lugo Dec 20 '20 at 04:10
  • this would actually be a viable solution: https://stackoverflow.com/a/33507307/6368401 – Heriberto Lugo Dec 20 '20 at 04:11
3
$(".parent").find("h2:contains('Statistics')").each(function(){
    var div=$(this).parent();
   // use div as you want
})

Working http://jsfiddle.net/SayjQ/

rahul maindargi
  • 5,359
  • 2
  • 16
  • 23
1

what about using HAS

$(".parent:has(h2:contains('Statistics'))")
DaFois
  • 2,197
  • 8
  • 26
  • 43
javi
  • 11
  • 3