I have a list of elements:
-
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:
//this is just to add event listeners
[...document.getElementsByClassName("abc")].forEach(e =>
e.addEventListener("click", ev => console.log(ev.target.innerText))
);
var wrapper = document.getElementsByClassName("wrapper")[0];
var items = [...wrapper.children];
const newOrder = [5,4,3,2,1,0]
items.sort((a, b)=>newOrder.indexOf(items.indexOf(a)) - newOrder.indexOf(items.indexOf(b)));
items.forEach(it=>wrapper.appendChild(it));
0
1
2
3
4
5
As you can see, if you click on 0, 1, etc, the event listener works.