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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 20:49:39  来源:igfitidea点击:

Using jquery how can I remove a DIV if it's contents are empty?

javascriptjquery

提问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_asidethat 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 divis 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();

http://jsfiddle.net/jasongennaro/L8dwn/1/

http://jsfiddle.net/jasongennaro/L8dwn/1/

回答by maheshwaghmare

To remove the element with idequal to removeme:

要删除id等于的元素removeme

$("#removeme").remove();

To remove the element with idequal to removemeonly 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

参考:使用jquery删除一个没有孩子的div