How do I do OuterHTML in firefox?

Here’s the function we use in pure.js:

function outerHTML(node){
    return node.outerHTML || new XMLSerializer().serializeToString(node);
}

To use it the DOM way:

outerHTML(document.getElementById('theNode'));

And it works cross browsers

EDIT: WARNING!
There is a trouble with XMLSerializer, it generates an XML(XHTML) string.
Which means you can end up with a tags like <div class="team" /> instead of
<div class="team"></div>
Some browsers do not like it. I had some pain with Firefox 3.5 recently.

So for our pure.js lib we came back to the old and safe way:

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);
  }

Leave a Comment