使用document.createElement创建的Element能否添加至另一文档?
能否将document.createElement创建的元素添加到另一个document?
可以直接将用document.createElement创建的元素添加到另一个document对象中,不过有个关键特性需要注意:元素会被从原文档的上下文转移到目标文档。
比如你给出的代码示例:
const element = document.createElement("div"); anotherDocument.body.appendChild(element)
执行这段代码后,这个div元素会脱离原本创建它的document上下文,成为anotherDocument的DOM树的一部分。如果这个元素之前已经挂载在原文档的DOM结构里,那么它会被从原位置移除,再添加到目标文档的body中。
另外,如果需要在目标文档里创建元素,也可以直接用目标文档的createElement方法,比如anotherDocument.createElement("div"),这样元素本身就属于目标文档的上下文,不需要转移操作。
内容的提问来源于stack exchange,提问作者ZhaoWei
相关产品推荐
相关产品推荐

