169 of 264 menu

cloneNode method

The cloneNode method allows you to clone an element and get its exact copy. This copy can then be inserted into a page using the prepend, append, appendChild, insertBefore or insertAdjacentElement methods.

The method receives either true or false as a parameter. If true is passed, then the element is cloned completely, together with all attributes and child elements, and if false - only the element itself (without child elements).

Syntax

element.cloneNode(true or false);

Example

We make a copy of the block with the class elem and paste it at the end of the #parent block:

<div id="parent"> <div class="elem"> <p>text1</p> <p>text2</p> </div> </div> let parent = document.getElementById('parent'); let elem = parent.querySelector('.elem'); let clone = elem.cloneNode(true); parent.appendChild(clone);

The code execution result:

<div id="parent"> <div class="elem"> <p>text1</p> <p>text2</p> </div> <div class="elem"> <p>text1</p> <p>text2</p> </div> </div>

Example

You can work with the resulting clone as with a regular element:

<div id="parent"> <div class="elem"> <p>text1</p> <p>text2</p> </div> </div> let parent = document.getElementById('parent'); let elem = parent.querySelector('.elem'); let clone = elem.cloneNode(true); clone.children[0].textContent = 'new text1'; clone.children[1].textContent = 'new text2'; parent.appendChild(clone);

The code execution result:

<div id="parent"> <div class="elem"> <p>text1</p> <p>text2</p> </div> <div class="elem"> <p>new text1</p> <p>new text2</p> </div> </div>

See also

  • the createElement method
    that can be used to create a new element
hihyenrosv