7

I can't use:

$('div:empty')

because the div might have empty spaces in it. I want to remove it if it has nothing or nothing but empty spaces.

5 Answers 5

11

This will return all div elements with no text apart from blank spaces (or other characters removed by .trim such as new line characters):

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

Update - based on comments

If any of the div elements in question have child elements which do not contain text (for example, img elements) 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;
});
4
  • Watch out, as if you have elements inside your div that don't have any text (like an image), it seem empty using this method. My answer takes care of this. $.trim($("<div>").append($("<img>").attr("src", "test")).text()) Sep 27, 2011 at 16:05
  • 1
    Yes, that's true. If that's the case for the OP, a combination of our answers should do the trick nicely! Sep 27, 2011 at 16:06
  • Seeing as your answer will be the first one seen by others looking for this, might you consider editing your post to mention that problem? Sep 27, 2011 at 16:07
  • Already on it :) and +1 to your answer too. (I've made it check explicitly for the empty string and length 0, even though they would coerce to false, just for clarity). Sep 27, 2011 at 16:09
7

Based on @Xeon06's answer, you can extend jQuery's selectors to find all elements with no 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)
};

usage for you would then be:

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

Live example: http://jsfiddle.net/JNZtt/

0
4

You could use this condition:

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

The additional children length check is to make sure that you don't consider a div with no text but other elements (for example, images) as empty.

1

You can do something like this:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.