How to duplicate a list item more than once using jQuery
I have few questions. Is it possible to duplicate multiple elements with jquery? I have one list of items, can I clone, duplicate it fe 7 times?
<ul id="my_list>
<li class="one_element>data</li>
</ul>
and some jquery, I have no idea how to write this:
var mylist = $('#my_list');
myList.find('li').clone(2);
Can you help me? thank.
var mylist = $('#my_list');
for ( i = 0; i < 7;i++){
mylist.find('li:first').clone().appendTo(mylist);
}
You can use $.each
the jQuery loop wrapper easily :
$.each(new Array(7),function(){
$('#list li:first').clone().appendTo('#list');
});
You can do it twice by hitching clones:
var mylist = $('#my_list');
myList.find('li:first').clone().appendTo(myList).clone().appendTo(myList);
var n=0;
var mclon = $('#my_list');
for ( i = 0; i < 7;i++){
mclon.clone().attr('id', 'id'+(n++) ).insertAfter( mclon );
}
Use .clone()
seven times.
Explanation: Thus, all seven clones are created with all unique IDs ( id=my_list+n
where n depends on the number of iterations).
If you don't need deep clones, you can use an array join()
to create an HTMLString corresponding to the n
number of elements, as shown below:
var elementString = new Array(++n).join($(selector).get(0).outerHTML)
which you can add to any element you want.
Basically we are passing the outerHTML of this element to an array method join()
that is 1
longer than the number of clones needed. This is because the method join()
starts adding after the first element and stops before the last one.
i.e,
[null,null,null,null].join(","); // results in ",,," not ",,,,"
In your case, you can do:
$("ul").append(new Array(8).join($(".one_element").get(0).outerHTML));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="my_list">
<li class="one_element">data</li>
</ul>