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