Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reorder html elements in dom

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.

like image 976
Toniq Avatar asked Jan 08 '16 20:01

Toniq


People also ask

What is the fastest way to query DOM?

getElementById is the fastest.


2 Answers

If you want a pure Javascript solution (no jQuery involved)

var arr = [2,1,0];
var wrapper = document.getElementsByClassName("wrapper");
var items = wrapper[0].children;
var elements = document.createDocumentFragment();

arr.forEach(function(idx) {
    elements.appendChild(items[idx].cloneNode(true));
});

wrapper[0].innerHTML = null;
wrapper[0].appendChild(elements);

A little improvement of my previous answer. Fiddle: https://jsfiddle.net/jltorresm/1ukhzbg2/2/

like image 171
j2e Avatar answered Oct 01 '22 01:10

j2e


Keep in mind that when you add an element that is already in the DOM, this element will be moved, not copied.

CodePen

let wrapper=document.querySelector(".wrapper");
let children=wrapper.children;
let newOrder=[3,2,1,0];
//it means that the first element you want it to be the four element
//The second element you want it to be the third
//the third element you want it to be the second
//the four element you want it to be the first
for(let i=0;i<newOrder.length;i++){
  for(let j=0;j<newOrder.length;j++){
    if(i==newOrder[j]){
      wrapper.appendChild(children[j]);
      break;
    }
  }
}
<div class="wrapper">
  <div>a</div>
  <div>b</div>
  <div>c</div>
  <div>d</div>
</div>
like image 20
John Balvin Arias Avatar answered Oct 01 '22 01:10

John Balvin Arias