gpt4 book ai didi

javascript - 查询 :contains selector without children

转载 作者:行者123 更新时间:2023-11-30 16:55:45 26 4
gpt4 key购买 nike

我需要做一个函数来更改 javascript(jquery) 中 dom 元素的颜色(在此示例中),但我在使用 :contains 选择器时遇到了一些麻烦,但我需要使用,因为我没有特定的 ID 或类。

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

关于javascript - 查询 :contains selector without children,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29751592/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com