📅  最后修改于: 2023-12-03 15:32:52.321000             🧑  作者: Mango
The cloneNode
method is a built-in JavaScript method that creates a copy of a DOM node. The copied node will have all the same attributes and child nodes as the original node. This method is particularly useful when creating duplicate elements on a web page or when manipulating the DOM.
newNode = node.cloneNode(deep);
node
: The DOM node that you want to copydeep
: A Boolean value that indicates whether or not to copy the node's children (true
for a deep copy, false
for a shallow copy)<body>
<div id="original">
<h1>Hello World</h1>
<p>This is some example text.</p>
</div>
</body>
<script>
// Get the original node
const originalNode = document.getElementById('original');
// Make a deep copy of the original node
const deepCopy = originalNode.cloneNode(true);
// Add the deep copy to the document
document.body.appendChild(deepCopy);
</script>
In this example, we create a deep copy of the originalNode
element using the cloneNode
method. We then add this copy to the end of the <body>
element using the appendChild
method.
cloneNode
method is only available in the browser environment and cannot be used in Node.js.cloneNode
method does not copy any event listeners that may be attached to the original node or its children, so these will need to be added separately if needed.