- To transform your array of indexes into a DocumentFragment, you can either use the Array spread syntax or the Array reduce method.
- Once you have your iterable ready, you can use the .append() method to add it to the same parent UL element.
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>
Comparing the performance between using DocumentFragment and Array destructuring with Spread syntax, the latter method is faster based on this benchmark test: this benchmark test
const liReordered = orderList.reduce((DF, i) => (DF.append(li[i]), DF), new DocumentFragment());
ul.append(liReordered);
One advantage of preserving events when reinserting elements using these methods is that any event already assigned to those LI elements will not be lost. This is different from 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>