How to detect if an HTML element is empty?

Asked

Viewed 13,879 times

13

How can I detect if an HTML element is empty with jQuery? I need to make a condition if the element is empty.

4 answers

15


Try this:

if ($('#element').is(':empty')){
  //seu codigo
}
  • Guys, I’m marking this because it was the one that worked, and despite having another one, it came first, before it was not working because the elements I wanted to check were loaded via ajax, but I’ve made the adjustments and it worked! Thank you all.

4

You can use .html().length to check the size of the element content.

Code example:

<div id="minhaDiv"></div>
<div id="minhaDiv2">2</div>
var div = $('#minhaDiv').html().length;     // dá 0
var div2 = $('#minhaDiv2').html().length;   // dá 1
div && console.log('Div 1: ' + div);        // não aparece
div2 && console.log('Div 2: ' + div2);      // aparece

Demo

4

Checking that it has no character (zero size):

if ($('seletor').is(':empty'))

Checking if it has no content (ignoring whitespace):

if ($.trim($('seletor').html()) == '')
  • It should be noted that in addition to the white spaces, $.Trim() will also remove line breaks and tabs that in Firefox and Chrome are considered as element content.

  • 1

    Your second option is bringing the following error: Uncaught Typeerror: Cannot call method 'Trim' of null

  • 1

    @Denisbernardo Experimenta: if ( $.trim( $('seletor').html() ) == '' ), that is, pass the collected content inside the TRIM and then compare.

  • @Zuul tested with if ( $.Trim( $('selector').html() == '' ) but is falling in if anyway

  • I added the note. @Denisbernardo, which browser you’re using?

  • @Talles It seems that $('seletor').html() is returning null, do not know under what conditions this could occur. Strange...

  • @bfavaretto, but the weird thing is that so much $.trim(null) how much $.trim(undefined) returned "" correctly with me (jQuery 2.0.2, Firefox 26).

  • I also tested it on jq2, maybe it happens in an earlier version. @Talles

  • @bfavaretto, in Jsfiddle with jQuery 1.10.1 worked normal: http://jsfiddle.net/4Wqm9/. @ Denis, was there any other error in your code?

Show 4 more comments

0

You can use

jQuery(document).ready(function () {

    //esta é uma alternativa mas pode falhar quando existem espaços em branco dentro da tag
    var test = jQuery("#elemento").html();
    if (test.length <= 0) {
        //elemento vazio.. faça algo
        alert("vazio");
    } else {
        //element possui html dentro...
        alert("não vazio");
    }

    //uma outra alternativa conta apenas os filhos dentro

    if (jQuery("#elemento").children().length <= 0) {
        //vazio
        alert("vazio");
    } else {
        //não vazio...
        alert("não vazio");
    }

    //se for verificar apenas o texto utilize .text() ao invés de .html()
});

an example is here

Browser other questions tagged

You are not signed in. Login or sign up in order to post.