AdrianD
AdrianD

Reputation: 279

JQuery select the parent 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!

Upvotes: 0

Views: 3489

Answers (3)

Pratik Deshmukh
Pratik Deshmukh

Reputation: 308

you can get parent element using :contains or filter function. If you are not able to get parent element using :contains or filter function you can use each loop:

var content = 'test';
var element = '';

$('.parent').each(function() {
    var inner_text = $(this).find('span').text();
    if(inner_text == content) {
        element = $(this);
    }
});

Upvotes: 1

bman
bman

Reputation: 21

If you are adamant about using the :contains() css selector then your code should look something like this:

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

Note the space between .parent and :contains(). This looks in the children individually for the given text and returns the element in which it was found. Then you must use .parent() to retrieve its parent element.

However, this will fail if the text that is placed into :contains() has special characters. It will also give false positives where a childs text contains the given text but does not exactly match it.

Instead, we can use a slightly modified version of the filter you posted:

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

Again, note that this filters through the children of the parent and not the parent itself.

Upvotes: 2

Powkachu
Powkachu

Reputation: 2268

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/.

Upvotes: 3

Related Questions