outerHTML for all the browsers

February 14th, 2008   Filed Under Javascript, snippet  

 I am sharing a very useful function outerHTML which is only implemented by IE for any HTML object type:

function outerHTML(obj)
{
var tsd = document.createElement("div");
var copyOb = obj.cloneNode(true);
tsd.appendChild(copyOb);
return tsd.innerHTML
}

So instead of {object}.outerHMTL you need to make call like this:
outerHTML({object});

How it works?
Basically the cloneNode method clones the node exactly how it appears in the DOM. Then the cloned node is pushed inside a dummy div. Now return the innerHTML of the dummy Div is the outerHTML of the passed object.

Works perfectly for all the browsers. So Enjoy!!!


Comments

Leave a Reply