获取 DOM 节点的字符串表示 [英] Get the string representation of a DOM node
本文介绍了获取 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.
推荐答案
可以创建一个临时的父节点,并获取它的innerHTML内容:
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>
请参阅下面有关outerHTML 的答案.el.outerHTML 应该是所有需要的.
Please see answer below about outerHTML. el.outerHTML should be all that is needed.
这篇关于获取 DOM 节点的字符串表示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文