Possible Duplicate:
Checking if an html element is empty with jQuery
I have an empty div like this:
<div id="cartContent"></div>
I need to check if it's empty. If it's empty it needs to return true and then some
elements are added. If not it returns false and some other function executes. What's the best way to check if there are any
elements in the div?
Thanks
This question is related to
javascript
jquery
operators
if ($("#cartContent").children().length == 0)
{
// no child
}
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.
var empty = $("#cartContent").html().trim().length == 0;
Using plain javascript
var isEmpty = document.getElementById('cartContent').innerHTML === "";
And if you are using jquery it can be done like
var isEmpty = $("#cartContent").html() === "";
You can use the is function
if( $('#cartContent').is(':empty') ) { }
or use the length
if( $('#cartContent:empty').length ) { }
Source: Stackoverflow.com