如何使用 JQuery 选择没有特定子元素的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7258606/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:36:58  来源:igfitidea点击:

How to select elements which do not have a specific child element with JQuery

jqueryjquery-selectors

提问by Stephan

Is there a JQuery selector to select all elements which do nothave certain child element as a direct child? For example:

是否有一个 JQuery 选择器来选择所有没有特定子元素作为直接子元素的元素?例如:

<p>
    text in paragraph
</p>
<p>
    <div>text in div</div>
</p>

I want to select only <p>s like the first one (without a <div>child). Is this possible?

我只想选择<p>第一个(没有<div>孩子)。这可能吗?

Further information: Actually I'm trying to insert a <div>into all those <p>that do not have one by an expression like this:

更多信息:实际上,我试图通过这样的表达式将 a 插入<div>到所有没有的那些<p>中:

$('p').wrapInner('<div />')

But this would add an additional <div>to the second <p>.

但这会给<div>第二个<p>.

回答by jmans

You could try:

你可以试试:

$("p:not(:has(>div))")

回答by Peter Olson

You can combine the :has()[docs]selector with the notfunction[docs]to acheive this:

您可以将:has()[docs]选择器与not函数[docs]结合起来实现:

$("p").not(":has(div)").wrapInner("<div/>");

Alternatively, you can use a single selector by using the :not()[docs]selector:

或者,您可以使用:not()[docs]选择器来使用单个选择器:

$("p:not(:has(div))").wrapInner("<div/>");

You can use either interchangeably, but IIRC, the first is faster.

您可以互换使用,但 IIRC,第一个更快。

See it in action on jsFiddle.

在 jsFiddle 上查看它的实际效果

Note that divis a block-level element and pis not. That means it is not valid HTML to have a divnested in a p.

请注意,这div是一个块级元素,p而不是。这意味着div嵌套在p.

回答by meo

structural elements inside text elements look very unclean to me but if you insist ;)

文本元素中的结构元素对我来说看起来很不干净,但如果你坚持;)

$('p').not(":has(div)").wrapInner("<div/>");

here is a demo: http://jsfiddle.net/NTpES/3/

这是一个演示:http: //jsfiddle.net/NTpES/3/

回答by ShankarSangoli

Try this:

尝试这个:

$("p").filter("not(:has(div))").wrapInner("<div/>");

回答by Blazemonger

This seems to work: $('p:not("p div")')

这似乎有效: $('p:not("p div")')