简体   繁体   中英

Jquery clone method to clone mutliple (more than one) div's (not a single div multiple times) inside a page

I need a method to clone say 4 div's with id's like d_1, d_2, d_3, d_4 including the contents inside each div all at once and then detach all divs, and then I need to find copy of d_1 and its contents from the clone and append it again to the page.

something like:

        var cloned=$('[id^="d_"]').clone();

        $('[id^="d_"]').detach();

and then find div with id =d_1 from clone and append it to body.

Is it possible?

You can appendTo() an element to detach and move an element elsewhere.

var els = $('[id^="d_"]')

els.detach();

els.each(function() {
  if (this.id.indexOf('d_1') !== -1) {
    $(this).appendTo(document.body);
  }
});

// do something else with els later, too.

Use Document Fragment.

var $documentFragment = $(document.createDocumentFragment());
$('[id^="d_"]').each(function(){
   $documentFragment.append($(this).clone().addClass("_cloned"));
});

$documentFragment.clone().appendTo(document.body);

If you want looking for an element into the fragment, you can do this:

$(document.body).find("#d_1._cloned"). ... ;

If you want to remove all the element and then append only the first copied into fragment:

$("._cloned", document.body).remove();
$documentFragment.find("#d_1").clone().appendTo(document.body);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM