Nested Sort on pre-rendered lists

Sometimes you might need to sort the items on a server-rendered list. Nested Sort can help you with this as long as your list structure looks like the one below:

<ul id="draggable">
  <li data-id="1">Item 1</li>
  <li data-id="2">Item 2</li>
  <li data-id="3">Item 3
    <ul data-id="3">
      <li data-id="31">Item 3-1</li>
      <li data-id="32">Item 3-2</li>
      <li data-id="33">Item 3-3</li>
    </ul>
  </li>
  <li data-id="4">Item 4</li>
</ul>

Now you only need to run the following JS code:

new NestedSort({
  el: '#draggable', // selector of your list
})

Multiple instances

Let's imagine a document which contains the following code:

<h2>List 1</h2>
<ul class="draggable">
  <li data-id="1">Item 1</li>
  <li data-id="2">Item 2</li>
  <li data-id="3">Item 3
    <ul data-id="3">
      <li data-id="4">Item 4</li>
    </ul>
  </li>
  <li data-id="5">Item 5</li>
</ul>

<h2>List 2</h2>
<ul class="draggable">
  <li data-id="2">Item 2
    <ul data-id="2">
      <li data-id="1">Item 1</li>
      <li data-id="3">Item 3</li>
    </ul>
  </li>
  <li data-id="4">Item 4</li>
  <li data-id="5">Item 5</li>
</ul>

In order to sort list items on both of those lists the following JS code can be used:

document.querySelectorAll('.draggable').forEach(function (list) {
  new NestedSort({
    el: list, // the DOM node
  });
})