3

i have i little question. Is there any option to duplicate more than one element with jquery? I have one element list, can i clone, duplicate it f.e. 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 u help me? Thx.

Lukas
  • 7,384
  • 20
  • 72
  • 127
  • What do you want to do with the clones? – nnnnnn Jan 31 '13 at 12:37
  • nothing special, but i need to minimalize my html – Lukas Jan 31 '13 at 12:38
  • What I'm getting at is do you want to immediately add them to that same list (or otherwise insert them into the DOM), or do you want to store them for later insertion? And do you want them to be identical or will you need to change attributes or content? Because the "best" solution might vary depending on your intention... – nnnnnn Jan 31 '13 at 12:43
  • yeah for later insertion by ajax action, but i need to do this by js site – Lukas Jan 31 '13 at 12:44

5 Answers5

4
var mylist = $('#my_list');
for ( i = 0; i < 7;i++){
      mylist.find('li:first').clone().appendTo(mylist);
}
Anton
  • 32,245
  • 5
  • 44
  • 54
2

You can easy use $.each jquery loop wrapper:

$.each(new Array(7),function(){
    $('#list li:first').clone().appendTo('#list');
});
r.piesnikowski
  • 2,911
  • 1
  • 26
  • 32
0

You can do it twice by chaining the clones:

var mylist = $('#my_list');
myList.find('li:first').clone().appendTo(myList).clone().appendTo(myList);
techfoobar
  • 65,616
  • 14
  • 114
  • 135
0
  var n=0;
  var mclon = $('#my_list');
 for ( i = 0; i < 7;i++){
  mclon.clone().attr('id', 'id'+(n++) ).insertAfter( mclon );
  }

Use .clone() for seven times.

Explanation:This way all seven clones are created with all having unique ids(id=my_list+n where n depends on number of iterations).

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
0

If you don't want deep clones, then you can use the array join() method to create an HTMLString corresponding to n number of elements as shown below:

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

which you can append to any element you wish.

Basically we pass the outerHTML of the element to an arrays join() method, whose length is 1 more than the number of clones required. This is because the join() method starts appending after the first element and stops prior to 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>
T J
  • 42,762
  • 13
  • 83
  • 138