Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create string from HTMLDivElement

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>
like image 397
Matthew Brown Avatar asked Nov 21 '10 18:11

Matthew Brown


2 Answers

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.

like image 171
BGerrissen Avatar answered Oct 15 '22 22:10

BGerrissen


You can use this function (taken from pure.js)

function outerHTML(node){
 return node.outerHTML || new XMLSerializer().serializeToString(node);
}
like image 28
Christoffer Klang Avatar answered Oct 15 '22 22:10

Christoffer Klang