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

JavascriptJquery

Javascript Problem Overview


I'm trying to call a function only if an HTML element is empty, using jQuery.

Something like this:

if (isEmpty($('#element'))) {
    // do something
}

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

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

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

Solution 3 - Javascript

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 - Javascript

!elt.hasChildNodes()

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

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

Happy now?

Solution 5 - Javascript

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

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

Solution 6 - Javascript

If by "empty", you mean with no HTML content,

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

Solution 7 - Javascript

In resume, there are many options to find out if an element is empty:

1- Using html:

if (!$.trim($('p#element').html())) {
	// paragraph with id="element" is empty, your code goes here
}

2- Using text:

if (!$.trim($('p#element').text())) {
	// paragraph with id="element" is empty, your code goes here
}

3- Using is(':empty'):

if ($('p#element').is(':empty')) {
	// paragraph with id="element" is empty, your code goes here
}

4- Using length

if (!$('p#element').length){
    // paragraph with id="element" is empty, your code goes here
}

In addiction if you are trying to find out if an input element is empty you can use val:

if (!$.trim($('input#element').val())) {
	// input with id="element" is empty, your code goes here
}

Solution 8 - Javascript

Empty as in contains no text?

if (!$('#element').text().length) {
    ...
}

Solution 9 - Javascript

Another option that should require less "work" for the browser than html() or children():

function isEmpty( el ){
  return !el.has('*').length;
}

Solution 10 - Javascript

You can try:

if($('selector').html().toString().replace(/ /g,'') == "") {
//code here
}

*Replace white spaces, just incase ;)

Solution 11 - Javascript

document.getElementById("id").innerHTML == "" || null

or

$("element").html() == "" || null

Solution 12 - Javascript

Vanilla javascript solution:

if(document.querySelector('#element:empty')) {
  //element is empty
}

Keep in mind whitespaces will affect empty, but comments do not. For more info check MDN about empty pseudo-class.

Solution 13 - Javascript

if($("#element").html() === "")
{

}

Solution 14 - Javascript

Are you looking for jQuery.isEmptyObject() ?

http://api.jquery.com/jquery.isemptyobject/

Solution 15 - Javascript

Here's a jQuery filter based on https://stackoverflow.com/a/6813294/698289

$.extend($.expr[':'], {
  trimmedEmpty: function(el) {
    return !$.trim($(el).html());
  }
});

Solution 16 - Javascript

JavaScript

var el= document.querySelector('body'); 
console.log(el);
console.log('Empty : '+ isEmptyTag(el));
console.log('Having Children : '+ hasChildren(el));


function isEmptyTag(tag) { 
    return (tag.innerHTML.trim() === '') ? true : false ;
}
function hasChildren(tag) {
    //return (tag.childElementCount !== 0) ? true : false ; // Not For IE
    //return (tag.childNodes.length !== 0) ? true : false ; // Including Comments
    return (tag.children.length !== 0) ? true : false ; // Only Elements
}

try using any of this!

document.getElementsByTagName('div')[0];
document.getElementsByClassName('topbar')[0];

document.querySelectorAll('div')[0];
document.querySelector('div'); // gets the first element.

Solution 17 - Javascript

Try this:

if (!$('#el').html()) {
    ...
}

Solution 18 - Javascript

Line breaks are considered as content to elements in FF.

<div>
</div>
<div></div>

Ex:

$("div:empty").text("Empty").css('background', '#ff0000');

In IE both divs are considered empty, in FF an Chrome only the last one is empty.

You can use the solution provided by @qwertymk

if(!/[\S]/.test($('#element').html())) { // for one element
	alert('empty');
}

or

$('.elements').each(function(){  // for many elements
    if(!/[\S]/.test($(this).html())) { 
    	// is empty
    }
})

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionvittoView Question on Stackoverflow
Solution 1 - JavascriptEmilView Answer on Stackoverflow
Solution 2 - JavascriptSerge ShultzView Answer on Stackoverflow
Solution 3 - JavascriptDMTintnerView Answer on Stackoverflow
Solution 4 - Javascriptuser663031View Answer on Stackoverflow
Solution 5 - JavascriptAlienWebguyView Answer on Stackoverflow
Solution 6 - JavascriptDigital PlaneView Answer on Stackoverflow
Solution 7 - JavascriptRuiVBoasView Answer on Stackoverflow
Solution 8 - JavascriptjensgramView Answer on Stackoverflow
Solution 9 - JavascriptdahlbykView Answer on Stackoverflow
Solution 10 - JavascriptMarc UbersteinView Answer on Stackoverflow
Solution 11 - JavascriptbrenView Answer on Stackoverflow
Solution 12 - JavascriptMaxView Answer on Stackoverflow
Solution 13 - JavascriptAlexView Answer on Stackoverflow
Solution 14 - JavascriptZubair1View Answer on Stackoverflow
Solution 15 - JavascriptDanHView Answer on Stackoverflow
Solution 16 - JavascriptYashView Answer on Stackoverflow
Solution 17 - JavascriptSyedView Answer on Stackoverflow
Solution 18 - JavascriptCorneliuView Answer on Stackoverflow