JQuery.html vs .attr ('innerHTML')

If I set the contents of a div element in my dom:

$("#myE").html(contents); 

Is there any difference between the above and:

 $("#myE").attr('innerHTML', contents); 

? Thanks!

+4
source share
4 answers

The second option will create an attribute (if it does not exist) called "innerHTML" in the dom element with id 'myE' and set the value for the content. The first option sets the html content of the dom element with the identifier "myE" to all content.

The first option will result in

 <div id="myE"> whatever the value of 'contents' is </div> 

The second option will result in (if "myE" is a div)

 <div id="myE" innerHTML="whatever_contents_value_is"> ... </div> 
+5
source

jAndy writes the following here: jQuery html () vs. innerHTML

.html () will just call .innerHTML after doing some checks for nodeType etc. It also uses a try / catch block, where it first tries to use innerHTML, and if that fails, it will gracefully be discarded by jQuerys.empty () + append ()

We hope this clarifies the situation.

+6
source

The difference is that in the second example, you directly use the innerHTML property to enter code in the DOM, bypassing some jQuery compatibility levels that provide cross-browser compatibility to avoid problems with some browsers, especially IE.

Therefore, the jQuery html() method is always the best solution. Not to mention that with the introduction of jQuery 1.6, there have been huge changes in the way you handle attributes and properties that will make your code unconditional incomaptibile if you decide to switch from jQuery 1.5.x to 1.6.x. They saw it.

+1
source

I don't think there is any difference between the html () call to innerHTML:

 html: function( value ) { if ( value === undefined ) { return this[0] && this[0].nodeType === 1 ? this[0].innerHTML.replace(rinlinejQuery, "") : null; // See if we can take a shortcut and just use innerHTML } else if ( typeof value === "string" && !rnocache.test( value ) && (jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) && !wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) { value = value.replace(rxhtmlTag, "<$1></$2>"); try { for ( var i = 0, l = this.length; i < l; i++ ) { // Remove element nodes and prevent memory leaks if ( this[i].nodeType === 1 ) { jQuery.cleanData( this[i].getElementsByTagName("*") ); this[i].innerHTML = value; } } // If using innerHTML throws an exception, use the fallback method } catch(e) { this.empty().append( value ); } } else if ( jQuery.isFunction( value ) ) { this.each(function(i){ var self = jQuery( this ); self.html( value.call(this, i, self.html()) ); }); } else { this.empty().append( value ); } return this; }, 

This snippet from jQuery source code

Hope this helps

0
source

All Articles