AdrianD AdrianD - 3 months ago 11x
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">
<span class="parent" id="2">
<span>some text</span>
<span class="parent" id="n">

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 );


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

Any help would be greatly appreciated, Thank you!


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: