Introduction to using cloneNode() in JavaScript to copy nodes
cloneNode() is a method in JavaScript that is used to copy a node. It can be used to create a copy of a node without affecting the original node.
The cloneNode() method has an optional boolean parameter deep, with a default value of false. When deep is false, only the current node will be copied, without its children. When deep is true, the children will also be copied along with the current node.
The cloneNode() method returns a new node object that can be inserted into other parts of the document using methods like appendChild() or insertBefore().
Here is an example of how to use the cloneNode() method:
var originalNode = document.getElementById("original");
var clonedNode = originalNode.cloneNode(true); // 拷贝节点及其子节点
document.body.appendChild(clonedNode); // 将拷贝的节点插入到body中
In the above example, the node with the id “original” is first retrieved using the getElementById() method. Then, the cloneNode() method is used to copy this node and insert the copied node into the body of the document.
Please note that the cloneNode() method only copies the attributes and values of the node itself, not event handlers. If you need to copy event handlers, you can use the addEventListener() method to attach them to the cloned node.
Furthermore, the cloneNode() method can only be used to duplicate DOM nodes and not other non-DOM objects like JavaScript objects.