Tuesday, June 4, 2024
 Popular · Latest · Hot · Upcoming
23
rated 0 times [  30] [ 7]  / answers: 1 / hits: 62291  / 14 Years ago, sun, november 21, 2010, 12:00:00

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>

More From » arrays

 Answers
47

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.


[#94888] Thursday, November 18, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mary

Total Points: 432
Total Questions: 98
Total Answers: 98

Location: Luxembourg
Member since Tue, Jan 25, 2022
2 Years ago
;