355

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

Something like this:

if (isEmpty($('#element'))) {
    // do something
}
Coleman
  • 565
  • 7
  • 15
vitto
  • 17,510
  • 29
  • 87
  • 128

17 Answers17

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

Emil
  • 7,949
  • 3
  • 25
  • 44
  • 56
    Line breaks are considered as content to elements in FF and Chrome. – Corneliu Jul 25 '11 at 08: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 '13 at 12:37
  • 2
    This is brilliant :-D – jasonbradberry Mar 29 '15 at 20:57
  • HTML comments are considered content too. – Paolo Jul 23 '15 at 17:52
  • 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 09 '16 at 15:52
  • Is this equivalent to: `if(row===row.empty())` ? – iloo Jun 03 '16 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 '16 at 06:52
  • "the browser interpretation of an empty element can vary" It doesn't, at all. Every browser considers an element that contains whitespace to *not* be empty for the purposes of the :empty selector, even if you don't consider jQuery's implementation. More likely, the browser interpretation of an empty element is at odds with what *authors* consider to be emptiness. – BoltClock Mar 16 '17 at 12:49
  • @Paolo: No, they're not. Not for the purposes of :empty anyway. – BoltClock Mar 16 '17 at 12:49
  • Thank you a lot! Amazing answer ;) – Joe Hackerberg Oct 01 '18 at 18:19
  • I found myself trying to use this a few times when the element isn't already wrapped in jQuery, which produces an error on `el.html()`. To fix that, I've modified it always wrap jQuery around the provided element like so: `function isEmpty(el){ return !$.trim($(el).html()); }` – brandonjp Aug 28 '19 at 15:34
119

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

if($.trim($("selector").html())=='')
Serge Shultz
  • 5,518
  • 3
  • 24
  • 16
  • 21
    A slightly more compressed version can take advantage of empty string's falsy-ness: `if(!$.trim($("selector").html())` – Brandon Belvin Aug 08 '13 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 '14 at 18:07
  • 1
    I think you're confusing "elements" with "nodes". –  Jun 02 '15 at 20:05
  • 1
    $("selector").html().trim() === '' – user1156544 Jun 23 '17 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 08 '18 at 17:48
70

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();
}
DMTintner
  • 13,235
  • 4
  • 32
  • 31
  • 4
    I choosed that above because I had HTML comments in my DIV. – Paolo Jul 23 '15 at 17:53
  • 2
    By far the most elegant solution, should be the correct answer. – Christoffer Bubach Sep 22 '15 at 22:32
  • 7
    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. – sierrasdetandil Jan 05 '18 at 20:38
  • @sierrasdetandil for `select` elements is perfect. the condition can also be `if(! $el.children().length)`. – CPHPython Sep 18 '18 at 15:22
28
!elt.hasChildNodes()

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

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

Happy now?

  • 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 '14 at 05:12
  • 1
    If I consider whitespace-only to be empty `
    `, this statement will returns false. https://jsfiddle.net/ytliuSVN/0pdwLt46/
    – Penny Liu Jul 02 '18 at 01:17
19
jQuery.fn.doSomething = function() {
   //return something with 'this'
};

$('selector:empty').doSomething();
AlienWebguy
  • 73,720
  • 16
  • 109
  • 137
12

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

if($('#element').html() == "") {
  //call function
}
Digital Plane
  • 33,886
  • 6
  • 50
  • 58
  • 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 '13 at 12:36
9

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
}
RuiVBoas
  • 306
  • 4
  • 8
8

Empty as in contains no text?

if (!$('#element').text().length) {
    ...
}
jensgram
  • 29,088
  • 5
  • 77
  • 95
2

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

function isEmpty( el ){
  return !el.has('*').length;
}
dahlbyk
  • 67,544
  • 8
  • 95
  • 120
1
document.getElementById("id").innerHTML == "" || null

or

$("element").html() == "" || null
MayorMonty
  • 3,963
  • 2
  • 23
  • 40
1

You can try:

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

*Replace white spaces, just incase ;)

Marc Uberstein
  • 12,143
  • 3
  • 41
  • 68
  • Wouldn't `!/[\S]/.test($('Selector').html())` work better, once you find some whitespace you know it's not empty – qwertymk Jul 25 '11 at 08:44
  • Why the /i in the regex flags? Are there upper and lower case versions of the space character? – Alexis Wilke Mar 26 '14 at 03:45
  • thanks, updated my answer. I have no idea why I have added /i – Marc Uberstein Mar 26 '14 at 08:47
  • @AlexisWilke Yes there's \s lowercase space character and \S uppercase space character. –  Nov 07 '14 at 23:20
  • 1
    @RobertMallow, Maybe regex supports \S, however, Unicode defines whitespaces as Cc, Zs, Zl, Zp as shown here: http://www.unicode.org/Public/UNIDATA/PropList.txt -- upper case is Lu... – Alexis Wilke Nov 07 '14 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 http://www.ecma-international.org/ecma-262/5.1/#sec-15.10.2.12 – Alexis Wilke Nov 08 '14 at 00:13
-1

Are you looking for jQuery.isEmptyObject() ?

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

Zubair1
  • 2,660
  • 2
  • 27
  • 37
-1

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

$.extend($.expr[':'], {
  trimmedEmpty: function(el) {
    return !$.trim($(el).html());
  }
});
Community
  • 1
  • 1
DanH
  • 4,628
  • 2
  • 43
  • 68
-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.
​
Yash
  • 7,342
  • 2
  • 55
  • 63
-1

Try this:

if (!$('#el').html()) {
    ...
}
Syed
  • 11,612
  • 10
  • 82
  • 122
-1
if($("#element").html() === "")
{

}
Alex
  • 7,134
  • 1
  • 16
  • 31
-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
    }
})
Corneliu
  • 2,884
  • 1
  • 17
  • 22