最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin5浏览0评论

I'm looking for a way to remove the following empty div using jquery.

The following div is output sometimes without content inside it. For display reasons I need to remove it when it's empty.

<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.

I'm looking for a way to remove the following empty div using jquery.

The following div is output sometimes without content inside it. For display reasons I need to remove it when it's empty.

<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.

Share Improve this question edited Jun 25, 2011 at 21:25 user456814 asked Jun 25, 2011 at 21:18 Bryan CaslerBryan Casler 6173 gold badges10 silver badges20 bronze badges 3
  • 2 Are you only targeting divs with that exact set of classes? – Chris Laplante Commented Jun 25, 2011 at 21:19
  • 2 Giving a div the class div is kind of redundant. – ThiefMaster Commented Jun 25, 2011 at 21:25
  • Actually I am targeting any empty div with the class field-group-format – Bryan Casler Commented Jun 25, 2011 at 21:30
Add a ment  | 

2 Answers 2

Reset to default 10

This works, assuming you don't have other div.group_call_to_action_aside that you want to keep:

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. ;-)

http://jsfiddle/jasongennaro/L8dwn/

EDIT

Yes, as per your mment, you can also do this

$('.group_call_to_action_aside:empty').remove();

http://jsfiddle/jasongennaro/L8dwn/1/

To remove the element with id equal to removeme:

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

To remove the element with id equal to removeme only if it is empty:

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

To remove all empty <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

发布评论

评论列表(0)

  1. 暂无评论