28

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

Community
  • 1
  • 1
user208709
  • 415
  • 1
  • 7
  • 12
  • [jQuery's :empty selector](http://api.jquery.com/empty-selector/) – Ohgodwhy Jan 26 '13 at 09:50
  • 23
    I disagree with this being marked duplicate. The question is about determining empty elements in javascript. Not jQuery. There are plenty of use cases where this subtle difference is significant. – newshorts Aug 31 '15 at 19:08
  • 1
    Not everyone has access to jQuery on a project and the question does not specifically mention jQuery. It's not a duplicate, even if answered in a duplicate way. –  Dec 07 '16 at 17:38
  • I guess this is tagged with "jquery" so maybe the OP really was trying to ask the duplicate question. – augurar Sep 14 '20 at 05:34
  • I agree with the sentiment that this is not a duplicate. The other post specifically asks about a jQuery solution and only jQuery solutions are provided there. Please read the question carefully before closing a post. – Eight Lives Dec 07 '22 at 22:23

6 Answers6

57

Using plain javascript

 var isEmpty = document.getElementById('cartContent').innerHTML === "";

And if you are using jquery it can be done like

 var isEmpty = $("#cartContent").html() === "";
dopeddude
  • 4,943
  • 3
  • 33
  • 41
  • OP is looking for jQuery. Also, `==` is evil. `===` is preferred. – Ian Atkin Jan 26 '13 at 09:53
  • 1
    `document.getElementById('cartContent').html` --> `undefined`, no matter what the actual element was. – Teemu Jan 26 '13 at 09:57
  • 14
    `!element.hasChildNodes()` –  Jan 26 '13 at 12:18
  • NOTE: element.hasChildNodes() does NOT work if the content is programmatically removed. Much more reliable to call `xx.innerHTML` or else `xx.children.length` which as subtly different! – John Henckel Jan 11 '20 at 18:11
43

You can use native JavaScript:

if document.getElementById('cartContent').innerHTML === "" {

You can use .is():

if( $('#leftmenu').is(':empty') ) {

Or you could just test the length property to see if one was found:

if( $('#leftmenu:empty').length ) {

You can use $.trim() to remove whitespace (if that's what you want) and check for the length of the content:

if( !$.trim( $('#leftmenu').html() ).length ) {
Ian Atkin
  • 6,302
  • 2
  • 17
  • 24
  • 1
    Copying and trimming the HTML can have undesirable performance impact if that div can sometimes be huge. I actually had problems with this approach in the past when my tested element was either empty (text nodes with whitespace only) or contained a lot of HTML. See my answer to see what I recommend. – rsp Jan 26 '13 at 10:13
  • @rsp Agree. As with anything JavaScript, once your data gets big in various ways, it's time to start looking at 'lazy' data handling. In most basic applications, though, this technique will work fine. As always, architecture and the size and type of data should be considered when designing an application. – Ian Atkin Jan 26 '13 at 19:18
  • This can return unexpected results. .is(':empty') can return false even if the actual element is empty of html. I think this might be because spaces and line breaks are counted. – bob Aug 31 '21 at 10:59
  • @bob Which is why I talk about removing whitespace and checking the length of the content as an alternative. – Ian Atkin Sep 01 '21 at 14:54
10

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.

rsp
  • 107,747
  • 29
  • 201
  • 177
7

You can use the is function

if( $('#cartContent').is(':empty') ) { }

or use the length

if( $('#cartContent:empty').length ) { }
muthu
  • 5,381
  • 2
  • 33
  • 41
4
var empty = $("#cartContent").html().trim().length == 0;
Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
1
if ($("#cartContent").children().length == 0) 
{
     // no child
}
Iswanto San
  • 18,263
  • 13
  • 58
  • 79