如何使用 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
How to select elements which do not have a specific child element with JQuery
提问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 not
function[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,第一个更快。
Note that div
is a block-level element and p
is not. That means it is not valid HTML to have a div
nested 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")')