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.
Keep in mind that when you add an element that is already in the DOM, this element will be moved, not copied.
CodePen
If you want a pure Javascript solution (no jQuery involved)
A little improvement of my previous answer. Fiddle: https://jsfiddle.net/jltorresm/1ukhzbg2/2/
I know this is an old question, but google lead me to it. There is a sub property on flexbox (css) called 'order', that allow you to choose the order that elements are displayed. Is possible to use javascript to change this sub property and reorder the displayed elements.
https://www.w3schools.com/cssref/css3_pr_order.asp
Edit 1 - code example:
This solution works better for me, we build an array of elements (
[...wrapper.children]
) then we use.sort
based on a model ([5,4,3,2,1,0]) and then we use appendChild. Since the elements are the same as the originals, the event listeners remain working fine. Here the code:As you can see, if you click on 0, 1, etc, the event listener works.
no need to copy all items .. twice