使用 jquery 删除没有孩子的 div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/527246/
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
Use jquery to remove a div with no children
提问by Sophie Alpert
How can I use jquery to remove a SPECIFIC div that has no children (at least no children that isn't whitespace). E.g.
我如何使用 jquery 删除没有孩子的特定 div(至少没有不是空白的孩子)。例如
<div id="outer">
some content
<div id="removeme">
</div>
some more content
</div>
Want to completely remove the div with id="removeme".
想要完全删除 id="removeme" 的 div。
回答by Sophie Alpert
To remove the element with id
equal to removeme
:
要删除id
等于的元素removeme
:
$("#removeme").remove();
To remove the element with id
equal to removeme
only if it is empty:
仅当它为空时才删除id
等于的元素removeme
:
$("#removeme:empty").remove();
To remove all empty <div>
s:
要删除所有空的<div>
s:
$("div:empty").remove();
EDIT:If it's not empty, but has whitespace:
编辑:如果它不是空的,但有空格:
if($.trim($("#removeme").text()) == "") {
$("#removeme").remove();
}
回答by Jonathan
I went with:
我去了:
$('#outer > div').filter(function (index) {
return $(this).children().length < 1;
}).remove();
This says:
这说:
- give me all the div children of #outer
- use filter to get rid of any which have child nodes
- remove anything we still have selected
- 给我 #outer 的所有 div 孩子
- 使用过滤器去除任何有子节点的
- 删除我们仍然选择的任何内容
Sadly, this will remove the div if it contains text, which is probably not what the original poster would have wanted. Plain text doesn't count as a child.
可悲的是,如果它包含文本,这将删除 div,这可能不是原始海报想要的。纯文本不算作孩子。
回答by rmurphey
You can also use:
您还可以使用:
$('div:empty').remove();
$('div:empty').remove();
回答by Simon Dragsb?k
Here is if empty with children then you can point at children and then remove a parent, this dont look at whitespaces it just remove if empty
这是如果有孩子是空的,那么你可以指向孩子然后删除父母,这不看空格它只是在空时删除
so like; if li is empty it removes #removeme
如此喜欢;如果 li 为空,则删除 #removeme
if (!$("#tabs ul li").length) $('#tabs').remove();
回答by Samantha Branham
I couldn't find a selector that ignores text nodes, so this is the quickest/dirtiest code snippet I could come up with.
我找不到忽略文本节点的选择器,所以这是我能想到的最快/最脏的代码片段。
$("#header").each(function() {
if($(this).children().length < 1)
$(this).remove()
});
回答by Luca Matteis
I think you want this:
我想你想要这个:
$('div#outer div:empty').remove();
It will remove all the empty divs inside the div#outer node
它将删除 div#outer 节点内的所有空 div