I found this function (although, I forgot where):
function outerHTML(node){ // if IE, Chrome take the internal method otherwise build one return node.outerHTML || ( function(n){ var div = document.createElement('div'), h; div.appendChild( n.cloneNode(true) ); h = div.innerHTML; div = null; return h; })(node); }
but this function works by calling outerHTML(my_element) , not my_element.outerHTML
I want to be able to extend the object of the javascript DOM element so that it has an outerHTML element, but use it if it exists anyway. how to do it?
The main reason I want to do this is because Firefox does not have an outerHTML method, but I still want to use my own implementations if they are available, since they passed the test, and I feel I can trust them.
UPDATE: @Raynos suggested that I do not do the above for outerHTML, and I should do something like the outerHTML specification. I found this: How to make outerHTML in firefox? and it does not .cloneNode, which may cause errors in FireFox 8.0.1.
So my solution is this: @Raynos:
if (!("outerHTML" in HTMLElement.prototype)) { Object.defineProperty(HTMLElement.prototype, "outerHTML", { get: getOuterHTML }); } function getOuterHTML(){ var parent = this.parentNode; var el = document.createElement(parent.tagName); el.appendChild(this.cloneNode(true)); var shtml = el.innerHTML; return shtml; }
source share