How to clone an element in Javascript?

13

Is it possible to get an exact clone of a particular HTML element? so that the clone contains all the properties exactly the same?

If there is one, I would like to know how to proceed with this clone, and also to understand how it is acting, how it would be cloning, or a more conceptual theory covering the clone itself.

    
asked by anonymous 05.02.2014 / 14:53

2 answers

11

Answering the question: Yes, there is a possibility to get a clone, using native javascript, which would or would not (you already know why) an exactly same faithful clone containing all element properties cloned.

Concept / Explanation: HTML elements in their format as you can see, like HTML code between tags, they are not just that. Each element is a Node , which is stored within the DOM (Document Object Model) where all the information, functions available for use, reference, attributes, values, among others, are summarized, everything an element is , is stored in DOM , without it we would not be able to access the properties of the elements directly. So to get an identical and exact copy of another element, we can clone the Node of it, in this way we would be cloning what it is.

Information / Examples / Practice: Every Node has a native Javascript function called cloneNode() , where now I explain why I said "or not" early on making a faithful clone , which would be the parameter deep of the function cloneNode() , which is a required parameter, ie you have to inform it, let's know this function:

cloneNode ([deep])

  

Arguments

     

deep ( Boolean ) required

     

If true ( true ), duplicate the subtree of Node as if it were itself.

     

If false ( false ), it only copies the node (and its attributes, if it is an element).

     

Description

     

Creates a copy (duplicate) of this Node , including all attributes, and their values, and attributes, including those that are not defined but contains a default value in DOM . The Node duplicate, there is no parent ( parent ), that is, parentNode is null, only while you do not include it in the document, for example using appendChild .      

However, if the deep argument is true ( true ), then the Node subtree will also be duplicated.

     

Additional Information

     

When cloning a subtree that is as readonly (read-only), it would result in a subtree that can not be modified.

     The attributes of the Node of the element, when cloned, are also copied, including the default attributes ( default ), but the element text is not copied, only if the deep argument is true ( true ).

     

Attention, Important Information about Events (credits to @bfavaretto):

     

The Clone will not have the events of the cloned element, if you assigned it as property or with addEventListener (most recommended methods, incidentally), the only way clone events work is when the event is inline or be: <div onclick=alert('foo')> for example.

     

If you want to understand better, there is an example Here

     

Return Value:

     

O Node duplicated (cloned).

Well, now that we know the function, let's practice:

Testing with deep clone (parameter deep = true):

Note: Please use an element that has children for better understanding.

var seuNode = document.getElementById('IDdoElementoQueTemFilhos'); //usei getElementById() por opção você pode resgatar a referência do seu node como quiser.
var clone   = seuNode.cloneNode(true); //aqui você terá seu clone armazenado em variável mas ainda não incluido no Documento, sem parentNode.
document.body.appendChild(clone); //você pode dar append onde quiser, utilizei o body.

Testing with clone only (deep = false parameter):

var seuNode = document.getElementById('IDdoElementoQueTemFilhos'); //usei getElementById() por opção você pode resgatar a referência do seu node como quiser.
var clone   = seuNode.cloneNode(false); //aqui você terá seu clone armazenado em variável mas ainda não incluido no Documento, sem parentNode.
document.body.appendChild(clone); //você pode dar append onde quiser, utilizei o body.

Note that for example 1, you have got the clone of it complete, including the children it has, that is, its subtree.

Now for example 2, you only get the clone of the isolated element, only it, without getting the copy of the children too (subtree).

Depending on its usage you can switch between the two methods of cloning. There are also other ways even using .clone() of jQuery, however, I'd consider it best to use this way that has clone fidelity of a Node and is javascript native, not requiring external plugins.

    
05.02.2014 / 14:53
2

In jQuery there is the jQuery.clone method that allows you to clone elements (with or without their respective events)

Consider the following example

HTML Structure

<div class="wrapper">
    <div class="exemplo">Uma div</div>
</div>

Javascript Code

// Evento simples de clique
$('.exemplo').on('click', function() {
    alert('Evento click');
});

// Clona o elemento com classe "exemplo"
var $clone = $('.exemplo').clone();

// Clona o elemento com classe "exemplo" juntamente com seus eventos
var $cloneComEventos = $('.exemplo').clone(true);

// Adiciona os elementos clonados no elemento wrapper
$('.wrapper').append($clone);
$('.wrapper').append($cloneComEventos);

The wrapper element will have a total of 3 elements, the first (original) and third (its copy) will have click events

In practice: link

    
07.02.2014 / 14:38