How to detect empty div using jQuery?

I can not use:

$('div:empty') 

because a div can have empty space in it. I want to remove it if it has nothing or nothing but empty spaces.

+7
source share
5 answers

This will return all div elements without text except spaces (or other characters removed by .trim , such as .trim characters):

 var emptyDivs = $("div").filter(function() { return $.trim($(this).text()) === ""; }); 

Refresh - Based on Comments

If any of the div elements has child elements that do not contain text (for example, img ), then the above method will include them in the set of "empty" elements. To exclude them, you can use the following:

 var emptyDivs = $("div").filter(function() { return $.trim($(this).text()) === "" && $(this).children().length === 0; }); 
+11
source

Based on @ Xeon06's answer, you can extend your jQuery selector to find all elements without content:

 $.expr[':'].nocontent = function(obj, index, meta, stack){ // obj - is a current DOM element // index - the current loop index in stack // meta - meta data about your selector // stack - stack of all elements to loop // Return true to include current element // Return false to explude current element return !($.trim($(obj).text()).length) && !($(obj).children().length) }; 

for you would be:

 $('div:nocontent').remove(); 

Real-time example: http://jsfiddle.net/JNZtt/

+7
source

You can use this condition:

 if (!$.trim($("div").text()).length && !$("div").children().length) 

An additional check on the length of children is to make sure you don't consider a div without text, but other elements (like images) are empty.

+4
source
 if ($.trim($('div').html()) == '') { $("div").remove(); } 
+1
source

You can do something like this:

 $('div:empty').each(function(){ if($.trim($(this).html()).length == 0){ //do what you want here... } }); 
0
source

All Articles