Copy list items from one list to another using jQuery

I am trying to get a list of items from one list and put it in another list.

This is what I have:

$("#change").click(function () { arr = $('#old').map(function () { return $(this).text(); }).get(); $.each(arr, function (index, item) { $('#test').append($( "<ul><li>" + item + " at " + index +"</li>" )); }); }); 

HTML:

 <ul id="old"> <li>One</li><li>Two</li><li>Three</li> </ul> <ul id="new"></ul> 

This will take elements from old and put it in new . It seems that it puts all elements in one <li> when it puts it in new .

+4
source share
4 answers

Just clone() and appendTo() first enter a new list:

 $('#old > li').clone().appendTo('#new'); 

And then change their text() :

 $('#new > li').text(function (index, text) { return text + ' at ' + index; }); 

Working demo: http://jsfiddle.net/vkYUQ/ .


Or, combine the above into one statement:

 $('#old > li').clone().text(function (index, text) { return text + ' at ' + index; }).appendTo('#new'); 
+3
source
 $(document).ready(function() { $("#change").click(function() { var old = $("#old"); var items = $("#old li"); var newList = $("#new"); items.each(function(index, value){ newList.append(value); }); old.empty(); return false; }); }); 
+3
source

Made a violin for the game:

http://jsfiddle.net/yEgMK/1/

Now clone() is one way, copying .html() is different, and there may be several others. Check out the differences in the jQuery API:

http://api.jquery.com/clone/ http://api.jquery.com/html/

0
source

You can use data() to copy and store your HTML in data

 var $old=$('#old'); $old.data('myhtml',$old.html()); 

To paste a copy in #test you can do

 var x = $old.data('myhtml'); $(x).appendTo('#test'); 
0
source

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


All Articles