在 mozill api docs对于outerHTML,当看到outerHTML
时:
Replaces the element with the nodes generated by parsing the string content with the parent of element as the context node for the fragment parsing algorithm.
但是,当我在控制台中尝试此操作时,它不起作用:
var d = document.createElement('div')
d.outerHTML = '<p>Some Text</p>'
console.log(d) //<div>
有人可以向我解释一下为什么这没有按预期工作吗?
//编辑:根据评论,我应该将其附加到渲染上下文中。以下仍然无效对我有用:
var d = document.createElement('div')
document.body.appendChild(d)
d.outerHTML = '<p>Some Text</p>'
console.log(d) //<div>
//EDIT2:查看生成的源,该元素确实被替换了。但是,d
仍然是一个 div。嗯——这很令人困惑。为什么会这样?
最佳答案
MDN docs有关于为什么 div 元素被替换的答案,并且 console.log(d)
引用原始 div 而不是替换的内容:
...while the element will be replaced in the document, the variable whose outerHTML property was set will still hold a reference to the original element...
关于javascript - 设置 node.outerHTML 不会执行任何操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45036833/