Is there a way in jQuery to clone an element's content? Not the entire element, only the content(children).
Something similar to what .html()
is doing, but I'm also interested in cloning the events attached to the content.
I was looking at .clone
, but it seems that is cloning the entire element.
Thanks.
Doua Beri, with reference to the jQuery API documentation for .clone()
you will find that what you want is .clone(true,true)
. This will make a deep copy of an element (or a collection of elements), including all data and event bindings.
You then have a choice of two options as to how you use .clone(true,true)
.
Clone the children individually to give a jQuery collection comprising clones of the children.
var $childClones = $("#myElement").children().clone(true,true);
Clone the outer element to give a jQuery collection comprising a clone of the outer element, itself containing clones of the children.
var $clone = $("#myElement").clone(true,true);
It is somewhat academic which approach you adopt. In both cases the descendant elements are available collectively or individually to be manipulated and/or inserted into the DOM, though the code to do so would differ slightly.
If you like a deep-copy just clone the children:
$('#footer-flair').children().clone()
And instead of attaching events to particular elements attach an event to a container element that is listening to child elements, that way your events will fire as long as the container element stays even if you add/remove a thousand elements inside the container. You could do this on the body tag if you never want your events to go away.
Use the 'on' method to bind events like so:
$('body').on('click', 'button.className', function(){
alert('button clicked');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With