DOM 节点的克隆和导入

前言
在使用 JS 操作 DOM 节点的时候,我们常常会用到克隆(或导入)节点的操作,那到底有哪些方法可以实现节点克隆(或导入)的效果呢?
今天,我们就来总结一下能实现节点克隆(或导入)效果的方法。
node.cloneNode()" class="reference-link">node.cloneNode()
提到克隆节点,我们最先能想到的肯定是 node.cloneNode() 方法。
语法
其语法如下:
let cloneNode = targetNode.cloneNode(deep);
- cloneNode 最终克隆生成的节点副本。
- targetNode 将要被克隆的目标节点。
- deep 可选参数,表示是否需要进行深度克隆,即是否需要克隆 targetNode 下的子节点,默认为 false。
举例:
<body><div id="container"><div class="header">这是头部</div><div class="body"><div class="content">内容一</div><div class="content">内容二</div></div></div><script>const target = document.querySelector(".body");const cloneNode1 = target.cloneNode();console.log("cloneNode1.outerHTML\n\n",cloneNode1.outerHTML);const cloneNode2 = target.cloneNode(true);console.log("cloneNode2.outerHTML\n\n", cloneNode2.outerHTML);</script></body>
运行结果如下:

document.importNode()" class="reference-link">document.importNode()
将外部文档的一个节点拷贝一份,然后可以把这个拷贝的节点插入到当前文档中。语法如下:
let node = document.importNode(externalNode, deep);
- node 从外部导入到当前文档的节点对象。
- externalNode 外部文档中将要被导入的目标节点。
- deep 是否深拷贝,默认为 false。
举例:
<!--iframe.html--><body><h1>这是 Iframe 页面</h1><div id="container"><div class="header">这是 Iframe 内容头部</div><div class="body">这是 Iframe 内容主体</div></div></body><!--index.html--><body><div id="container"><div class="header">内容头部</div><div class="body">内容主体</div></div><iframe id="iframe_ele" src="./iframe.html"></iframe><script>window.onload = function () {const iframeEle = document.getElementById('iframe_ele');const iframeContainer = iframeEle.contentDocument.getElementById("container");const importedNode = document.importNode(iframeContainer, true);document.body.appendChild(importedNode);}</script></body>
最终效果如下:

document.adoptNode()" class="reference-link">document.adoptNode()
从其他的document文档中获取一个节点。 该节点以及它的子树上的所有节点都会从原文档删除 (如果有这个节点的话), 并且它的ownerDocument 属性会变成当前的document文档。 之后你可以把这个节点插入到当前文档中。语法:
let node = document.adoptNode(externalNode);
- node 从外部文档中获取到的节点对象。
- externalNode 将要被导入的外部文档中的节点对象。
举例:
<!--iframe.html--><body><h1>这是 Iframe 页面</h1><div id="container"><div class="header">这是 Iframe 内容头部</div><div class="body">这是 Iframe 内容主体</div></div></body><!--index.html--><body><div id="container"><div class="header">内容头部</div><div class="body">内容主体</div></div><iframe id="iframe_ele" src="./iframe.html"></iframe><script>window.onload = function () {const iframeEle = document.getElementById('iframe_ele');const iframeContainer = iframeEle.contentDocument.getElementById("container");const node = document.adoptNode(iframeContainer);document.body.appendChild(node);}</script></body>
效果:

总结
以上就是使用 JS 克隆(或导入)DOM 节点的方法总结。
~
~ 本文完,感谢阅读!
~
学习有趣的知识,结识有趣的朋友,塑造有趣的灵魂!
大家好,我是〖编程三昧〗的作者 隐逸王,我的公众号是『编程三昧』,欢迎关注,希望大家多多指教!