jQuery jquery删除直接子元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4805933/
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
jquery remove direct child element
提问by Prashant
Using jQuery, how can I remove an anchor tag in my html body which also consists of a wrapper div, and this wrapper div is above the anchor tag that I want to remove.
使用 jQuery,如何删除我的 html 正文中的锚标记,它也包含一个包装 div,并且这个包装 div 位于我要删除的锚标记上方。
It is like
它像是
<body>
<div id="wrapper">
<a id="not_me" href="#">hi</a>
</div>
<a id="remove_me" href="#">Remove Me</a>
</body>
If I use
如果我使用
$("body").find("a:first-child").remove();
it removes the first anchor tag in my wrapper div i.e. one with id "not_me", while I want "remove_me" to be removed.
它删除了我的包装器 div 中的第一个锚标记,即 ID 为“not_me”的一个,而我希望删除“remove_me”。
回答by user113716
$("body").children("a:first").remove();
You use children()
(docs)because you only want to target direct children of body
.
您使用children()
(docs)是因为您只想定位body
.
Then use "a:first"
as the selector to target the first <a>
element.
然后"a:first"
用作选择器来定位第一个<a>
元素。
This is because with the first-child-selector
(docs)you'll only get the <a>
ifit is the first child of its parent (which it isn't). But with the first-selector
(docs)you get the first <a>
that was matched.
这是因为与first-child-selector
(文档)你只会得到<a>
,如果它是其父的第一个孩子(它不是)。但是使用first-selector
(文档)你会得到第一个<a>
匹配的。
Alternative would be to place it all in one selector:
另一种方法是将其全部放在一个选择器中:
$('body > a:first').remove();
Same as above, but uses the >
child-selector
(docs)instead of the children()
(docs)method.
同上,但使用>
child-selector
(docs)而不是children()
(docs)方法。
回答by mVChr
You want to use children()
to search on direct children only, and you can use :first
or eq(0)
to remove the first one:
您只想用于children()
搜索直接子级,并且可以使用:first
或eq(0)
删除第一个:
$("body").children("a").eq(0).remove();
回答by psoares
why don't you try:
你为什么不试试:
$("#remove_me").remove()
don't know if it's wrong, I'm still learning :P
不知道是不是错了,还在学习中 :P