jQuery 检查元素是否有任何子元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6321067/
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
Check if element has any children?
提问by Alex Hope O'Connor
I am trying to remove an element from the DOM if it does not contain any elements.
如果一个元素不包含任何元素,我试图从 DOM 中删除它。
Here is what I tried:
这是我尝试过的:
var numChildren = 0;
$("#messages").children().each(function () {
numChildren += 1;
});
if (numChildren <= 0) {
$("#messages").slideUp("normal", function () { $(this).remove(); });
}
回答by Darin Dimitrov
var messages = $('#messages');
if (messages.children().length < 1) {
messages.slideUp('normal', function () { $(this).remove(); });
}
Don't forget though that this will remove the messages
div from the DOM.
不要忘记这会messages
从 DOM 中删除div。
回答by alexmuller
You could also simply use $("#messages:empty").remove();
, though you'd need to trim whitespace to make the element truly empty.
您也可以简单地使用$("#messages:empty").remove();
,但您需要修剪空格以使元素真正为空。