Jquery :包含没有 children 的选择器

Jquery :contains selector without children

我需要执行一个函数来更改 javascript(jquery) 中 dom 元素的颜色(在本例中),但我在使用 :contains 选择器时遇到了一些问题,但我需要使用,因为我没有特定的 ID 或 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 只是为了向您展示我的问题。

Js :

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

问题:

此脚本进行了不需要的更改 (#element2)

我已经检查过:Jquery doc 但在这个例子中要简单 dom 。

这里是可测试的例子:JSFIDDLE

尝试使用排除 div 和其他元素,

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

如果您的 html 有机会包含这样的元素,

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

那么最终你必须同意@TrueBlueAussie 的回答。

DEMO

您可以创建自己的过滤器来删除子元素并仅检查当前元素的文本节点。

由于您尝试匹配的字符串也存在于注释中,因此无法使用 innerHTML,因此使用 textContent

$("#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