Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
188
rated 0 times [  190] [ 2]  / answers: 1 / hits: 28374  / 9 Years ago, fri, january 8, 2016, 12:00:00

I have a list of elements:



<div class=wrapper>
<div class=abc></div>
<div class=abc></div>
<div class=abc></div>
</div>


And I have an array or numbers which represent new order:



var arr = [2,1,0];


I would like to reposition these abc divs to new positions inside parent wrapper.



Important thing is that abc divs have events and data attached to them and this needs to be preserved!



I have came up with this and it seems to be working as expected:



var wrapper = $('.wrapper'), items = wrapper.children('div.abc');

var orderedItems = $.map(arr, function(value) {
return $(items).clone(true,true).get(value);
});
wrapper.empty().html(orderedItems);


I wanted to make sure this is the right way.



I could do with javascript solution as well if possible.


More From » jquery

 Answers
40

no need to copy all items .. twice



var wrapper = $('.wrapper'), 
items = wrapper.children('.abc'),
arr = [2,1,0];

//items.detach(); if arr doesn't reuse all items
wrapper.append( $.map(arr, function(v){ return items[v] }) );

[#63792] Thursday, January 7, 2016, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
shamya

Total Points: 38
Total Questions: 101
Total Answers: 96

Location: Thailand
Member since Thu, Apr 22, 2021
3 Years ago
;