Like others have already noted, you can use :empty
in jQuery like this:
$('#cartContent:empty').remove();
It will remove the #cartContent
div if it is empty.
But this and other techniques that people are suggesting here may not do what you want because if it has any text nodes containing whitespace it is not considered empty. So this is not empty:
<div> </div>
while you may want to consider it empty.
I had this problem some time ago and I wrote this tiny jQuery plugin - just add it to your code:
jQuery.expr[':'].space = function(elem) {
var $elem = jQuery(elem);
return !$elem.children().length && !$elem.text().match(/\S/);
}
and now you can use
$('#cartContent:space').remove();
which will remove the div if it is empty or contains only whitespace. Of course you can not only remove it but do anything you like, like
$('#cartContent:space').append('<p>It is empty</p>');
and you can use :not
like this:
$('#cartContent:not(:space)').append('<p>It is not empty</p>');
I came out with this test that reliably did what I wanted and you can take it out of the plugin to use it as a standalone test:
This one will work for jQuery objects:
function testEmpty($elem) {
return !$elem.children().length && !$elem.text().match(/\S/);
}
This one will work for DOM nodes:
function testEmpty(elem) {
var $elem = jQuery(elem);
return !$elem.children().length && !$elem.text().match(/\S/);
}
This is better than using .trim
because the above code first tests if the tested element has any child elements and if it does it tries to find the first non-whitespace character and then stops, without the need to read or mutate the string if it has even one character that is not whitespace.
Hope it helps.