377

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

Something like this:

if (isEmpty($('#element'))) {
    // do something
}
1
  • $('#elem').text().match(/\S/) || alert('empty'); Jul 26, 2017 at 16:11

18 Answers 18

632
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.

8
  • 60
    Line breaks are considered as content to elements in FF and Chrome.
    – Corneliu
    Jul 25, 2011 at 8:46
  • @Corneliu is correct. I posted an answer below that takes that into consideration. This was a major source of frustration for me on a recent project
    – DMTintner
    Aug 28, 2013 at 12:37
  • Doing this with a function is nice of course, but if you want it more "embedded" (and a bit challenging), I would recommend manipulating the prototype of jQuery or using the great "filter" function ability of JQ...
    – TheCuBeMan
    Mar 9, 2016 at 15:52
  • Is this equivalent to: if(row===row.empty()) ?
    – iloo
    Jun 3, 2016 at 13:04
  • @iloo, .empty does not do what you think it does. It does not check if an element is empty, it does empty the element.. :)
    – Refilon
    Jun 20, 2016 at 6:52
125

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

if($.trim($("selector").html())=='')
6
  • 25
    A slightly more compressed version can take advantage of empty string's falsy-ness: if(!$.trim($("selector").html()) Aug 8, 2013 at 15:41
  • 11
    I don't think they consider them "elements", but they consider them nodes, which is IMO correct. You could also do if($("selector").children().length === 0) or if($("selector > *").length === 0).
    – panzi
    May 13, 2014 at 18:07
  • 1
    I think you're confusing "elements" with "nodes".
    – user663031
    Jun 2, 2015 at 20:05
  • 3
    $("selector").html().trim() === '' Jun 23, 2017 at 23:33
  • 1
    I do not know why but method from this answer: if($.trim($("selector").html())=='') worked. .is(':empty') did not!
    – some_guy
    Jun 8, 2018 at 17:48
79

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();
}
4
  • 5
    I choosed that above because I had HTML comments in my DIV.
    – Paolo
    Jul 23, 2015 at 17:53
  • 2
    By far the most elegant solution, should be the correct answer. Sep 22, 2015 at 22:32
  • 8
    Note that $.children() does not return text or comment nodes, which means this solution only checks is the element is empty of elements. If an element that contains only text or comments should not be considered empty for your needs, then you should use one of the other solutions. Jan 5, 2018 at 20:38
  • @sierrasdetandil for select elements is perfect. the condition can also be if(! $el.children().length).
    – CPHPython
    Sep 18, 2018 at 15:22
29
!elt.hasChildNodes()

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

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

Happy now?

3
  • 1
    +1 I used your approach inside a jQuery filter function as I didn't want to use jQuery inside the function unless necessary.
    – WynandB
    Apr 30, 2014 at 5:12
  • 1
    If I consider whitespace-only to be empty <div class="results"> </div>, this statement will returns false. jsfiddle.net/ytliuSVN/0pdwLt46
    – Penny Liu
    Jul 2, 2018 at 1:17
  • @PennyLiu which is correct because a space is a text node in an HTML document.
    – Jens
    Oct 12, 2021 at 7:12
19
jQuery.fn.doSomething = function() {
   //return something with 'this'
};

$('selector:empty').doSomething();
4
  • Great! I like constructions without ifs. Jul 25, 2011 at 8:24
  • totally agree with @Nikolay, It isn't useful for my specific situation but I'll remember it for the future!
    – vitto
    Jul 25, 2011 at 8:33
  • well, this wouldn't work when you have to apply 'this'
    – user1099258
    Feb 14, 2015 at 20:45
  • What else would this be besides the jQuery element @ZealMurapa ? Feb 14, 2015 at 23:42
13

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

if($('#element').html() == "") {
  //call function
}
1
  • careful, whitespace and line breaks could cause html to not == '' but element still be empty. Check my answer below for another solution
    – DMTintner
    Aug 28, 2013 at 12:36
11

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
}
8

Empty as in contains no text?

if (!$('#element').text().length) {
    ...
}
2
  • This doesn't address elements whose contents are images (don't ask how I came up with that...) Feb 3, 2016 at 16:47
  • 2
    @BadRequest No, hence the question mark after "as in contains no text?" :)
    – jensgram
    Apr 19, 2017 at 17:16
2

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

function isEmpty( el ){
  return !el.has('*').length;
}
1
  • Refers to jQuery’s has() function, not JavaScript’s Set.has() or Map.has(). Note, though, that the "*" selector selects only elements, and does not select e.g. text nodes. Thus, <p>text</p> would be considered empty.
    – Jens
    Oct 12, 2021 at 7:04
1

You can try:

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

*Replace white spaces, just incase ;)

6
  • Wouldn't !/[\S]/.test($('Selector').html()) work better, once you find some whitespace you know it's not empty
    – qwertymk
    Jul 25, 2011 at 8:44
  • Why the /i in the regex flags? Are there upper and lower case versions of the space character? Mar 26, 2014 at 3:45
  • thanks, updated my answer. I have no idea why I have added /i Mar 26, 2014 at 8:47
  • 1
    @RobertMallow, Maybe regex supports \S, however, Unicode defines whitespaces as Cc, Zs, Zl, Zp as shown here: unicode.org/Public/UNIDATA/PropList.txt -- upper case is Lu... Nov 7, 2014 at 23:57
  • 1
    @RobertMallow, also The production CharacterClassEscape :: S evaluates by returning the set of all characters not included in the set returned by CharacterClassEscape :: s. from ecma-international.org/ecma-262/5.1/#sec-15.10.2.12 Nov 8, 2014 at 0:13
1
document.getElementById("id").innerHTML == "" || null

or

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

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.

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

}
-1

Are you looking for jQuery.isEmptyObject() ?

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

1
  • 2
    This question is about empty DOM elements, not empty JavaScript objects. May 26, 2015 at 14:31
-1

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

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

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.
​
-1

Try this:

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

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
    }
})

Not the answer you're looking for? Browse other questions tagged or ask your own question.