One DOM element property that has been provided in Internet Explorer that isn’t natively available in some other browsers is outerHTML
. Fortunately there is a cross-browser solution for getting this property:
(function() {
/**
* Gets the HTML of the specified element including that
* of the element itself.
* @param {!Element}
* The element whose outer HTML will be returned.
* @return {string}
* The HTML code of the specified element.
*/
getOuterHTML = function(elem) {
if('outerHTML' in elem) {
return elem.outerHTML;
}
else {
var ownerDoc = elem.nodeType != 9
? elem.ownerDocument || elem.document
: elem;
var div = ownerDoc.createElement('div');
div.appendChild(elem.cloneNode(true));
return div.innerHTML;
}
};
})();
I actually can’t take the credit for this function because it is derived from Google’s Closure Library. The function can be used as follows:
// Display HTML for entire HTML document.
alert(getOuterHTML(document.documentElement));
If you are one of those people that needs to use this property in all browsers, I hope this code will help you. 8)