AdrianD AdrianD - 5 months ago 15
Javascript Question

JQuery select the parrent based on child containing exact text

I have the following problem I can seem to get working:

I have a set of parent spans containing a different set of tags but of which only 1 other span with a text inside. I want to extract the parents whose inner spans have the exact text match!



<span class="parent" id="1">
<p>..</p><p>..</p>
<span>text</span>
<a>..</a>
</span>
<span class="parent" id="2">
<span>some text</span>
<a>..</a>
</span>
....
<span class="parent" id="n">
<p>..</p>
<span>other</span>
</span>





When I search for "text" I want only the span with id == "1"

My original attempt with contains returns 2 spans -> id == 1 and id == 2:

var current = "text";
var element = $('.parent:contains(' + current + ')');


I have also tried with filter, which in my humble opinion should work but does not :(

var element = $('.parent').filter(function () {
return ($(this).children().text()==current );
});


or

var element = $('.parent').filter(function () {
return ($(this).children('span').text() == current )
});


Any help would be greatly appreciated, Thank you!

Answer

You can try:

var current = "text";
var test = $('.parent').children().filter(function() {
    return $(this).text() === current;
});

It looks like one of you solution but I tried mine and it worked. You can try it here: https://jsfiddle.net/amwadqm3/.