javascript - 设置 node.outerHTML 不会执行任何操作

标签 javascript html

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/

相关文章:

javascript - TinyMCE - 如何在同一页面上有 2 个编辑器,并且两个编辑器只有一个预览按钮

javascript - POST 表单只需要一个 select 标签

javascript - 如何使用 js 或 jquery 在单击时突出显示 html 表中的列?

javascript - 有多个 javascript 对象实例

javascript - Google 条形图 - 如何使用 JSON 为每个条目获取 2 个不同的条形图

javascript - 通过启用特定选项卡直接加载网页

css - Echoed div id 在 Safari 中有效,但在 Firefox、Chrome 或 Opera 中无效

javascript - HTML Canvas 上的第一行具有不同的宽度

javascript - 检测选择了什么表单自动完成值

Javascript 返回基于日期的平均测试结果数组