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

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

Check if element has any children?

jqueryhtmldom

提问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 messagesdiv 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();,但您需要修剪空格以使元素真正为空。