Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 999
Bryan Casler Avatar asked Jun 25 '11 21:06

Bryan Casler


People also ask

How do I hide a div if there is no content?

Hide empty divs - To hide the div set: display: none; in :empty selector · GitHub.

What does empty () do in jQuery?

The empty() method removes all child nodes and content from the selected elements. Note: This method does not remove the element itself, or its attributes. Tip: To remove the elements without removing data and events, use the detach() method. Tip: To remove the elements and its data and events, use the remove() method.

How do I clear a div content?

To clear the contents of a div element, set the element's textContent property to an empty string, e.g. div. textContent = '' . Setting textContent on the element removes all of its children and replaces them with a single text node of the provided value. Copied!

What is the difference between the remove () and empty () methods in jQuery?

remove() – Removes all child elements with selected element. In this method you can restore all data but not event handlers of removed elements from the DOM. All data and events related with elements will be removed. empty() – Removes all content and child elements from the selected element.


1 Answers

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.net/jasongennaro/L8dwn/

EDIT

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

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

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

like image 144
Jason Gennaro Avatar answered Nov 15 '22 05:11

Jason Gennaro