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.
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;
});
$.trim($("<div>").append($("<img>").attr("src", "test")).text())false, just for clarity).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/