Copying Elements
As noted above, if you insert elements that are already part of
the document, those elements will simply be moved, not copied, to their
new location. If you are inserting the elements in more than one place,
jQuery will make copies as needed, but copies are not made for only one
insertion. If you want to copy elements to a new location instead of
moving them, you must first make a copy with the clone()
method. clone()
makes and returns a copy of each
selected element (and of all descendants of those elements). The
elements in the returned jQuery object are not part of the document yet,
but you can insert them with one of the methods above:
// Append a new div, with id "linklist" to the document $(document.body) .append("<div id='linklist'><h1>Links</h1></div>"); // Copy all links in the document into that new div $("a").clone().appendTo("#linklist"); // Add a <br/> after each link so they don't run together $("#linklist > a").after("<br/>");
clone()
does not normally copy
event handlers (see Chapter 4) or other data you
have associated with elements (see Getting and Setting Element Data); pass
true
if you want to clone that
additional data as well.
Get jQuery Pocket Reference now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.