How do I check if an HTML element is empty using jQuery?

How do I check if an HTML element is empty using jQuery?

I’m trying to call a function only if an HTML element is empty, using jQuery.
Something like this:
if (isEmpty($(‘#element’))) {
// do something
}

Solutions/Answers:

Solution 1:

if ($('#element').is(':empty')){
  //do something
}

for more info see http://api.jquery.com/is/ and http://api.jquery.com/empty-selector/

EDIT:

As some have pointed, the browser interpretation of an empty element can vary. If you would like to ignore invisible elements such as spaces and line breaks and make the implementation more consistent you can create a function (or just use the code inside of it).

  function isEmpty( el ){
      return !$.trim(el.html())
  }
  if (isEmpty($('#element'))) {
      // do something
  }

You can also make it into a jQuery plugin, but you get the idea.

Solution 2:

I found this to be the only reliable way (since Chrome & FF consider whitespaces and linebreaks as elements):

if($.trim($("selector").html())=='')

Solution 3:

White space and line breaks are the main issues with using :empty selector. Careful, in CSS the :empty pseudo class behaves the same way. I like this method:

if ($someElement.children().length == 0){
     someAction();
}

Solution 4:

!elt.hasChildNodes()

Yes, I know, this is not jQuery, so you could use this:

!$(elt)[0].hasChildNodes()

Happy now?

Solution 5:

jQuery.fn.doSomething = function() {
   //return something with 'this'
};

$('selector:empty').doSomething();

Solution 6:

If by “empty”, you mean with no HTML content,

if($('#element').html() == "") {
  //call function
}