Reorder html elements in dom

后端 未结 5 501
眼角桃花
眼角桃花 2020-12-10 15:17

I have a list of elements:

5条回答
  •  半阙折子戏
    2020-12-10 16:09

    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.

提交回复
热议问题