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:

<ol id="draggable">
  <li data-id="1">Item 1</li>
  <li data-id="2">Item 2</li>
  <li data-id="3">Item 3
    <ol 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>
    </ol>
  </li>
  <li data-id="4">Item 4</li>
</ol>

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>
<ol class="draggable">
  <li data-id="1">Item 1</li>
  <li data-id="2">Item 2</li>
  <li data-id="3">Item 3
    <ol data-id="3">
      <li data-id="4">Item 4</li>
    </ol>
  </li>
  <li data-id="5">Item 5</li>
</ol>

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

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
  });
})