Cloning DOM Elements - J Query

You need to clone/copy a portion of the DOM.


jQuery provides the clone() method for copying DOM elements. Its usage is straight forward.Simply select the DOM elements using the jQuery function, and then call the clone() method on the selected set of element(s). The result is a copy of the DOM structure being returned for chaining instead of the originally selected DOM elements.In the following code, I am cloning the <ul>element and then appending this copy back into the DOM using the inserting method appendTo(). Essentially, I am adding another <ul>structure to the page exactly like the one that is already there:


The cloning method is actually very handy for moving DOM snippets around inside of the DOM. It’s especially useful when you want to not only copy and move the DOM elements but also the events attached to the cloned DOM elements. Closely examine the HTML and jQuery here:

If you were to run this code in a browser, it would clone the <li>elements on the page that have a click event attached to them, insert these newly cloned elements (including events) into the empty <ul>, and then remove the <ul>element that we cloned.
This might stretch a new jQuery developer’s mind, so let’s examine this jQuery statement by stepping through this code in order to explain the chained methods:

  1. jQuery('ul#a li') = Select <ul>element with an id attribute of a and then select all the <li>elements inside of the <ul>.

  2. .click(function(){alert('List Item Clicked')}) = Add a click event to each <li>.

  3. .parent() = Traverse the DOM, by changing my selected set to the <ul>element.

  4. .clone(true) = Clone the <ul>element and all its children, including any events attached to the elements that are being cloned. This is done by passing the clone() method a Boolean value of true.

  5. .find('li') = Now, within the cloned elements, change the set of elements to only the <li>elements contained within the cloned <ul>element.

  6. .appendTo('#b') = Take these selected cloned <li>elements and place them inside of the <ul>element that has an id attribute value of b.

  7. .end() = Return to the previous selected set of elements, which was the cloned

  8. .end() = Return to the previous selected set of elements, which was the original
    <ul>element we cloned.

  9. .remove() = Remove the original <ul>element.

If it’s not obvious, understanding how to manipulate the selected set of elements or revert to the previous selected set is crucial for complex jQuery statements.

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd Protection Status

J Query Topics