views:

115

answers:

2

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.

+2  A: 

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>
CMS
Ouch. So simple... Just a little note: If I want the whole document "stringified", I can use the same method with document.documentElement (usecase: AJAX requests). Perhaps you could incorporate that in the answer?
Boldewyn
@Boldewyn: you can append the entire `document.documentElement` into a div? Holy crap....
Roatin Marth
Yes. Really cool, isn't it? :-P
Boldewyn
+1  A: 

Under FF you can use the XMLSerializer object to serialize XML into a string. IE gives you an xml property of a node. So you can do the following:

function xml2string(node) {
   if (typeof(XMLSerializer) !== 'undefined') {
      var serializer = new XMLSerializer();
      return serializer.serializeToString(node);
   } else if (node.xml) {
      return node.xml;
   }
}
Bryan Kyle
FYI `.xml` doesn't work on DOM nodes (as in nodes in the current page). It only works on XML DOM document nodes.
Crescent Fresh
And conversely, `outerHTML` doesn't work on XML DOM document nodes. It only works on DOM nodes (as in nodes in the current page). Good consistency there I'd say.
Crescent Fresh