innerHTML() is native and returns the contents of a DOM node (e.g. <span>I live inside a div.</span>
. outerHTML() is not, which would include the current DOM node (e.g. <div><span>I live inside a div.</span></div>
). This is a chain-able jQuery version of doing that.
$.fn.outerHTML = function(){
// IE, Chrome & Safari will comply with the non-standard outerHTML, all others (FF) will have a fall-back for cloning
return (!this.length) ? this : (this[0].outerHTML || (
function(el){
var div = document.createElement('div');
div.appendChild(el.cloneNode(true));
var contents = div.innerHTML;
div = null;
return contents;
})(this[0]));
}
Am I missing something, seems like this is unnecessarily overcomplicating things, why couldn’t it be written like:
https://gist.github.com/3707775 ?
The snippet on this page returns a chain-able jQuery object.
That’s not true, the only time this would return a chainable jquery object is if there are no elements in the set:
return (!this.length) ? this : (this[0].outerHTML || (function(){ ... })());
if the jquery set is empty (length 0) then it returns
this
which is the jquery object that is chainable. Otherwise it tries to return the native htmlouterHTML
propery. If the native htmlouterHTML
property is null, then it calls the function, which also returns a string, not a jquery object.This snippet also doesn’t perform this on each element of the set, it only performs it on the first element (
this[0]
). However, that makes sense, it would be really weird to return an array of strings of html which would not be jquery objects.what is the el used here? lost…
It’s “this[0]”. More about this
How do we ever call the function