开发者

How to detect an empty div using jQuery?

开发者 https://www.devze.com 2023-04-08 08:27 出处:网络
I c开发者_StackOverflowan\'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.This will return all div elements

I c开发者_StackOverflowan'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.


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


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/


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.


You can do something like this:

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


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

精彩评论

暂无评论...
验证码 换一张
取 消