Get the string representation of a DOM node

Boldewyn picture Boldewyn · Nov 17, 2009 · Viewed 125.7k times · Source

Javascript: I have the DOM representation of a node (element or document) and I'm looking for the string representation of it. E.g.,

var el = document.createElement("p");
el.appendChild(document.createTextNode("Test"));

should yield:

get_string(el) == "<p>Test</p>";

I have the strong feeling, that I'm missing something trivially simple, but I just don't find a method that works in IE, FF, Safari and Opera. Therefore, outerHTML is no option.

Answer

Christian C. Salvad&#243; picture Christian C. Salvadó · Nov 17, 2009

You can create a temporary parent node, and get the innerHTML content of it:

var el = document.createElement("p");
el.appendChild(document.createTextNode("Test"));

var tmp = document.createElement("div");
tmp.appendChild(el);
console.log(tmp.innerHTML); // <p>Test</p>

EDIT: Please see answer below about outerHTML. el.outerHTML should be all that is needed.