38

In Jquery what is the difference between

$('#divid').html("");

and

$('#divid').empty();

Are both doing the same operating internally inside jQuery.js?

and which one is better to use.

2
  • 5
    The duplicate marking should include a link to the extant question
    – Evan
    Commented Dec 23, 2013 at 17:17
  • 2
    .empty() is much faster: jsperf.com/jquery-empty-vs-html/17
    – AmpT
    Commented Feb 28, 2014 at 22:32

3 Answers 3

37

T think .empty() is faster. This is the jQuery source for .empty()

empty: function() {
    var elem,
        i = 0;

    for ( ; ( elem = this[ i ] ) != null; i++ ) {
        if ( elem.nodeType === 1 ) {

            // Prevent memory leaks
            jQuery.cleanData( getAll( elem, false ) );

            // Remove any remaining nodes
            elem.textContent = "";
        }
    }

    return this;
}

And this is the jQuery .html("") source :

html: function( value ) {
    return access( this, function( value ) {
        var elem = this[ 0 ] || {},
            i = 0,
            l = this.length;

        if ( value === undefined && elem.nodeType === 1 ) {
            return elem.innerHTML;
        }

        // See if we can take a shortcut and just use innerHTML
        if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
            !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) {

            value = jQuery.htmlPrefilter( value );

            try {
                for ( ; i < l; i++ ) {
                    elem = this[ i ] || {};

                    // Remove element nodes and prevent memory leaks
                    if ( elem.nodeType === 1 ) {
                        jQuery.cleanData( getAll( elem, false ) );
                        elem.innerHTML = value;
                    }
                }

                elem = 0;

            // If using innerHTML throws an exception, use the fallback method
            } catch ( e ) {}
        }

        if ( elem ) {
            this.empty().append( value );
        }
    }, null, value, arguments.length );
}

It's clear, you can choose your best.

2
13

I tried the following in JSperf and found out using $('#divid').empty(); is better

enter image description here

4

From the source code of the html function, among many other things :

        if ( elem ) {
            this.empty().append( value );
        }

So html calls empty. Thus it's (marginally) faster to simply call empty. And of course it's more readable.

1
  • There is a lot more to the implementation html than this, if I'm interpreting it correctly it's not even running this code when you call html with an empty string.
    – Alex
    Commented Dec 28, 2020 at 9:17

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