user967451
user967451

Reputation:

How to detect an empty div using jQuery?

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.

Upvotes: 7

Views: 6746

Answers (5)

Korvin Szanto
Korvin Szanto

Reputation: 4501

if ($.trim($('div').html()) == '') { $("div").remove(); }

Upvotes: 1

Jamiec
Jamiec

Reputation: 136074

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/

Upvotes: 7

James Allardice
James Allardice

Reputation: 165941

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

Upvotes: 11

expertCode
expertCode

Reputation: 533

You can do something like this:

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

Upvotes: 1

Alex Turpin
Alex Turpin

Reputation: 47776

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.

Upvotes: 4

Related Questions