1

I have below code which works perfectly to sort DOM.

HTML:

<ul id="list">
     <li data-order="7"></li>
     <li data-order="6"></li>
     <li data-order="5"></li>
     <li data-order="3"></li>
     <li data-order="4"></li>
     <li data-order="1"></li>
     <li data-order="2"></li>
</ul>
<button>Sort</button>

CSS

li::before {
    content: attr(data-order);
    display: block;
}

Javascript with jQuery:

const sortList = function(a, b) {
    return (+a.dataset.order) - (+b.dataset.order) > 0 ? 1: - 1;
};

$('button').click(() => {
    $('#list li').sort(sortList).appendTo('#list');
});

Or you can check it on codepen: https://codepen.io/EdmondWang/pen/pozeyXb

I have 2 questions.

1. Why does not browser relayout DOM once sort function get called?

2. Why appendTo() is required to make sort work? (Even there is no detach)

Thank you for the help in advance!

Community
  • 1
  • 1
Edmond Wang
  • 1,687
  • 13
  • 27
  • 1
    Related: [Sorting a list by data-attribute](https://stackoverflow.com/q/32199368/4642212). – Sebastian Simon Aug 25 '19 at 05:43
  • 1
    I have no idea what you mean by your first question… the list gets sorted, doesn’t it? What do you mean by “relayout”? I’m also not sure why exactly you don’t understand the purpose of `appendTo`—you need to move the DOM elements to sort them; how else would you do that? – Sebastian Simon Aug 25 '19 at 05:47
  • @SebastianSimon, the accepted answer of related link resolve my questions. – Edmond Wang Aug 25 '19 at 05:54

0 Answers0