How to clone () an element n times?

I have a dynamic table in which I want to add <col> elements using jQuery.

I have it:

 var tds = jQuery("tr > td").length; // count how many tds jQuery("#colgroup-compare > col").clone() // clone .appendTo('#colgroup-compare'); // and append 

Obviously this only adds 1 <col> , I want to add (n) numbers. How can I do it?

I have a length, I have a clone ability, now how do I combine it?

+6
source share
3 answers

Using a loop:

 var $col = $("#colgroup-compare > col"); for(var i = 0; i < n; i++){ $col.clone().appendTo('#colgroup-compare'); } 

You cannot use jQuery("#colgroup-compare > col").clone().appendTo('#colgroup-compare'); in its loop because it will add more cols at iterations> 0 ...

This can be optimized:

 var $colgroup = $('#colgroup-compare'); // this saves the colgroup collection to avoid recomputing it later var $col = $colgroup.children("col"); // this makes the clonable col(s) from the col children of $colgroup for (var i=n; i-->0;){ // n times (from n-1 to 0) $colgroup.append($col.clone()); // append a clone of the col(s) } 

EDIT: to count th in your first line, you can do this:

 var n=$("tr").first().children('th').length; 

(this eliminates the need for multiple lines)

Demonstration

+6
source

Use the for loop:

 for(var i = 0; i < n; i++){ jQuery("#colgroup-compare > col").clone().appendTo('#colgroup-compare'); } 

It was fast and dirty, and I didn’t think about the effects of the coughing. dystroy solution is better.

0
source

If you don’t need deep clones, you can avoid manual iteration by passing the outerHTML of the element to join() arrays, resulting in an HTMLString corresponding to the number of elements n , as shown below:

 var elementString = new Array(++n).join($(selector).get(0).outerHTML) 

which you can add to any item you want.


In your case, you can do:

 var n= $("tr > td").length, $colgroup = $("#colgroup-compare"); $colgroup.append(new Array(++n).join($colgroup.find("col").get(0).outerHTML)); 
0
source

Source: https://habr.com/ru/post/927436/


All Articles