javascript 如果内容为空,如何使用 jquery 删除 DIV?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6480587/
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
Using jquery how can I remove a DIV if it's contents are empty?
提问by Bryan Casler
I'm looking for a way to remove the following empty div using jquery.
我正在寻找一种使用 jquery 删除以下空 div 的方法。
The following div is output sometimes without content inside it. For display reasons I need to remove it when it's empty.
下面的 div 有时会输出,里面没有内容。出于显示原因,我需要在它为空时将其删除。
<div class="field-group-format group_call_to_action_aside div group-call-to-action-aside box yellow speed-fast effect-none"></div>
Thoughts?
想法?
I've been trying the following and variations of it, but have't had any luck.
我一直在尝试以下及其变体,但没有任何运气。
回答by Jason Gennaro
This works, assumingyou don't have other div.group_call_to_action_aside
that you want to keep:
这有效,假设您没有其他div.group_call_to_action_aside
要保留的:
if ($('.group_call_to_action_aside').is(':empty')) {
$('.group_call_to_action_aside').remove();
}
Note: I've styled the div
, so you can see a brief flash of it before the js takes effect. but you won't see this when you do it because the div
is empty. ;-)
注意:我已经对 进行了样式设置div
,因此您可以在 js 生效之前看到它的简短闪光。但是当你这样做时你不会看到这个,因为它div
是空的。;-)
http://jsfiddle.net/jasongennaro/L8dwn/
http://jsfiddle.net/jasongennaro/L8dwn/
EDIT
编辑
Yes, as per your commment, you can also do this
是的,根据您的评论,您也可以这样做
$('.group_call_to_action_aside:empty').remove();
$('.group_call_to_action_aside:empty').remove();
回答by maheshwaghmare
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();
}
Reference: Use jquery to remove a div with no children