liveBook · Manning

Node cloning

As explained in Web Components in Action

cloneNode is a DOM method that creates a copy of a node, optionally including its entire descendant subtree.

To reuse an HTML template, clone its content before adding it to the page: `template.content.cloneNode(true)`. The `true` requests a deep clone, including the node’s children. Appending the fragment directly moves its contents and leaves it empty; cloning lets you append copies repeatedly. section 7.2

Listing 7.6. Cloning multiple times to add to our page
const template = document.getElementById('button');
const clone = template.content.cloneNode(true);          #1
document.body.appendChild(clone);                        #2
const clone2 = template.content.cloneNode(true);         #3
document.body.appendChild(clone2);                       #4

A button template is cloned and appended twice, demonstrating repeated use. section 7.2

How Web Components in Action covers it

How deep it goes
Defines true as cloning a node and its descendants, and contrasts cloning with fragment consumption without discussing cloning internals.
Examples
Demonstrates cloning a button-and-paragraph template once and twice into document.body.
What it assumes
Assumes basic element selection and DOM appending; teaches deep cloning but not those operations from zero.
What you can do after
Apply cloneNode(true) to append reusable template contents repeatedly.
How it connects
Connects DOM cloning with HTML templates, document fragments, and appending nodes.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Web Components in Action. The section links point to the parts of the book it draws on.