Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery clone only element's content

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.

like image 665
Doua Beri Avatar asked Jan 06 '13 02:01

Doua Beri


2 Answers

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).

  1. Clone the children individually to give a jQuery collection comprising clones of the children.

    var $childClones = $("#myElement").children().clone(true,true);

  2. 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.

like image 108
Beetroot-Beetroot Avatar answered Oct 22 '22 01:10

Beetroot-Beetroot


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');
});
like image 30
Julian Krispel-Samsel Avatar answered Oct 22 '22 00:10

Julian Krispel-Samsel