Skip to main content

Using the cloneNode Method in JavaScript DOM (Live Playground)

In this tutorial, we will learn how to use the cloneNode method in JavaScript DOM to duplicate elements in your web applications. This technique is useful for creating dynamic and interactive content.

What is the cloneNode Method?

The cloneNode method is a DOM method that allows you to create a copy of a specified element, including its attributes and content. You can choose to clone the element with or without its child elements by providing a boolean value (true or false) as an argument to the method.

  • true: The cloned element will include all child elements and their descendants.
  • false: The cloned element will only include the element itself and its attributes.

Example: Cloning an Element with cloneNode

Let's consider the following HTML structure:

<ul id="list">
<li class="item">Item 1</li>
<li class="item">Item 2</li>
<li class="item">Item 3</li>
</ul>

Now, we'll use the cloneNode method to clone the first list item and append it to the list:

const list = document.getElementById('list');
const firstItem = document.querySelector('.item');

const clonedItem = firstItem.cloneNode(true);
clonedItem.textContent = 'Cloned Item';

list.appendChild(clonedItem);

After executing this code, the updated HTML structure will be:

<ul id="list">
<li class="item">Item 1</li>
<li class="item">Item 2</li>
<li class="item">Item 3</li>
<li class="item">Cloned Item</li>
</ul>

In this example, we used the cloneNode(true) method to create a copy of the first list item, including its content. We then updated the text content of the cloned element and appended it to the list.

Live Playground, Try it Yourself

Conclusion

In this tutorial, we have learned how to use the cloneNode method in JavaScript DOM to duplicate elements in your web applications. This advanced DOM manipulation technique allows you to create dynamic and interactive content, such as adding new items to a list or duplicating form fields based on user input.