javascript - reorder a list without creating new list according to another list

Viewed 136

I have a HTML list on a page with several items, each of which contain not just text but also input and tables. I also have a list for order like [3,1,2,0].

Is it possible to reorder the HTML list on the page according to the order list without creating a new list i.e. only the re-ordered list but not the original list shows up on the page?

var ul = document.querySelector('ul');

const order = [3,1,2,0];
<ul>
<li>item1</li>
<li>item2</li>
<li>item3</li>
<li>item4</li>
</ul>

1 Answers

const orderList = [3, 1, 2, 0];

const ul = document.querySelector('#list');
const li = ul.querySelectorAll('li'); 
ul.append(...orderList.map(i => li[i]));
<ul id="list">
  <li>0</li>
  <li>1</li>
  <li>2</li>
  <li>3</li>
</ul>

Using DocumentFragment seems slightly slower than the above method using Array destructuring using the Spread syntax as per this benchmark test

const liReordered = orderList.reduce((DF, i) => (DF.append(li[i]), DF), new DocumentFragment());
ul.append(liReordered);

By doing so any event that's already assigned to that LI elements is preserved, therefore not lost by reinserting them into the DOM (like it would be the case by using innerHTML or insertAdjacentHTML etc)

const orderList = [3, 1, 2, 0];

const ul = document.querySelector('#list');
const li = ul.querySelectorAll('li'); 

li.forEach(el => el.addEventListener("click", () => {
  console.log("Events are preserved!");
}));

ul.append(...orderList.map(i => li[i]));
<ul id="list">
  <li>0 CLICK ME</li>
  <li>1 CLICK ME</li>
  <li>2 CLICK ME</li>
  <li>3 CLICK ME</li>
</ul>

Related