Create string from HTMLDivElement

Matthew Brown picture Matthew Brown · Nov 21, 2010 · Viewed 46.3k times · Source

What I would like to be able to do is create a string from a Javascript HTMLElement Object. For example:

var day = document.createElement("div");
day.className = "day";
day.textContent = "Random Text";

Now we have create the day HTMLDivElement Object is it possible to make it print as a string? e.g.

<div class="day">Random Text</div>

Answer

BGerrissen picture BGerrissen · Nov 21, 2010

Variant on Gump's wrapper, since his implementation lifts the target node out of the document.

function nodeToString ( node ) {
   var tmpNode = document.createElement( "div" );
   tmpNode.appendChild( node.cloneNode( true ) );
   var str = tmpNode.innerHTML;
   tmpNode = node = null; // prevent memory leaks in IE
   return str;
}

To print the resulting string on screen (re: escaped)

var escapedStr = nodeToString( node ).replace( "<" , "&lt;" ).replace( ">" , "&gt;");
outputNode.innerHTML += escapedStr;

Note, attributes like "class" , "id" , etc being stringified properly is questionable.