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.
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.
.empty()
is the boss! much faster: jsperf.com/jquery-empty-vs-html/17
I tried the following in JSperf and found out using $('#divid').empty(); is better
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.
html
than this, if I'm interpreting it correctly it's not even running this code when you call html
with an empty string.
.empty()
is much faster: jsperf.com/jquery-empty-vs-html/17