Cloning & Removing Elements

Open the project folder

In our starter files, open the index.html page from this lessons folder:

04.Events-And-The-DOM > 06.Cloning-and-Removing-elements

The cloneNode method

We begin by looking at cloning elements we already have. In the starter files, we have the same set up as previously used.

To clone an element we first need to select one. You can choose any, but for simplicity I will use the buttonElement we already have:

// ========= CLONING & REMOVING ELEMENTS =========
// 1.
buttonElement

// 2. On this button element node, we can call the cloneNode method:
buttonElement.cloneNode();

// 3. And then store it in a variable
const clonedButton = buttonElement.cloneNode();

Try to type clonedButton in the console, we get back the <button></button> element. But, there is nothing inside, not even the “BUY ONLINE” text we have set.

This is because cloneNode will simply clone the element node, not the contents.

Deep cloning

If we want the contents inside, we need to pass in a Boolean value of true, which will make it a deep clone:

const clonedButton = buttonElement.cloneNode(true);

Be careful when cloning that we don’t end up with duplicate id’s since we can only use an id once in a document. This also just creates the element, we need to add it to our web pages using appendChild or one of the other methods we have covered.

Removing elements

To remove elements we have the remove and also removeChild methods. The remove method is simple. We select our node, and then call the remove method on it:

// ========= CLONING & REMOVING ELEMENTS =========
// const clonedButton = buttonElement.cloneNode(true);

// remove h3:
sectionHeading.remove();

Using this same example of removing the h3, another way of doing this is on the parent. Looking at our commented out HTML this is wrapped in a section:

<!-- <section>
  <h3>Helping the planet, one bite at a time...</h3>

The h3 is a child of this section wrapper.

We also have a reference to it here:

// ========= WRAPPERS =========
const sectionWrapper = document.createElement('section');

So, we can select this and remove anything directly inside by calling removeChild:

// ========= CLONING & REMOVING ELEMENTS =========
// Comment out previous example:
// const clonedButton = buttonElement.cloneNode(true);
// sectionHeading.remove();
sectionWrapper.removeChild(sectionHeading);

You should by now have a good idea of how we work with the DOM using JavaScript. They follow a similar pattern of selecting elements, storing them, and calling methods on them to do certain things like remove them, add them to another element to construct our HTML exactly how we want it to be.