获取DOM节点的字符串表示形式

问题描述:

Javascript:我有一个节点(元素或文档)的DOM表示,我正在寻找它的字符串表示。例如

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"));

应产生:

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

我有强烈的感觉,我错过了一些简单的东西,找到一个工作在IE,FF,Safari和Opera的方法。因此,outerHTML不是选项。

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.

可以创建一个临时父节点, p>

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>