📜  mdn clonenode (1)

📅  最后修改于: 2023-12-03 15:32:52.321000             🧑  作者: Mango

MDN cloneNode

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.

Syntax
newNode = node.cloneNode(deep);
  • node: The DOM node that you want to copy
  • deep: A Boolean value that indicates whether or not to copy the node's children (true for a deep copy, false for a shallow copy)
Example
<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.

Notes
  • The cloneNode method is only available in the browser environment and cannot be used in Node.js.
  • The 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.