Benjamin Poignant
Benjamin Poignant

Reputation: 1064

Jquery :contains selector without children

I need to do a function to change color (in this example) of dom element in javascript(jquery) but i have some trouble with :contains selector but i need to use because i don't have specific ID or class.

HTML :

<p id="title">John</p><!-- contain John must be red -->

<div id="description">John</div><!-- contain John must be red -->


<div id="element">
    <p id="element1">John</p><!-- contain John must be red -->
    <p id="element2">Anonymous</p><!-- dont contain John dont change color -->
</div>

ID in this code just to show you my problem.

Js :

$("div:contains('John'), p:contains('John')").css("color", "red");

Problem :

This script make unwanted changes (#element2)

I already check : Jquery doc but to simple dom in this example .

Testable example here : JSFIDDLE

Upvotes: 1

Views: 423

Answers (2)

adeneo
adeneo

Reputation: 318352

You could create your own filter that removes children elements and checks the textNodes of the current element only.

As the string you're trying to match is present in the comments as well, any use of innerHTML is out, so textContent is used.

$("#bug").on('click', function () {

    $("div, p").filter(function() {
        var clone = this.cloneNode(true);

        while (clone.firstElementChild) {
            clone.removeChild(clone.firstElementChild);
        }

        return clone.textContent.indexOf('John') != -1;
    }).css("color", "red");

});

FIDDLE

Upvotes: 1

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67217

Try to use exclude the div with other elements,

$("div:contains('John'):not(:has(*)), p:contains('John')").css("color", "red");

If your html have chances of containing elements like this,

<div id="description">John<p>test</p></div>

Then ultimately you have to go along with @TrueBlueAussie's answer.

DEMO

Upvotes: 2

Related Questions