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
source share