JavaScript如何将对象document.createElement转换为字符串

5

无法获取一个字符串,将其分配给一个变量,该字符串使用createElement

var h1 = document.createElement("h1")
h1.innerHTML = "hello world"
alert(h1)
return "[object HTMLHeadingElement]"

当我使用appendChild时,它是有效的,但我必须使用警告或其他方法。

为什么你不能只是 alert(h1.innerHTML) 呢? - elclanrs
可能是 h1.toString() 吗? - Ivan Chernykh
2个回答

21

使用outerHTML

var h1 = document.createElement("h1")
h1.innerHTML = "hello world"
alert(h1.outerHTML)

演示: Fiddle


3
我经常忘记这件事。我想我还停留在 Firefox 4 版本 ;) - Felix Kling

0

看起来你想将一个DOM元素转换为它的HTML表示形式。将其放入临时容器中并访问其.innerHTML属性:

var div = document.createElement('div');
div.appendChild(h1);
var html = div.innerHTML;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接