Changing the order of elements

For this simple case (swapping the only two elements), you can just use appendChild():

(() => {
  const list = document.querySelector("ul");
  list.appendChild(list.firstElementChild);
})();
<ul>
  <li>List-item #1</li>
  <li>List-item #2</li>
</ul>

The same node cannot exist in multiple positions; so, it’s removed from its current position and placed at the end of the collection.

If you want to do more complicated sorting, you probably ought to create an array from the childNodes and get all crazy:

(() => {
  const frag = document.createDocumentFragment();
  const list = document.querySelector("ul");
  const items = list.querySelectorAll("li");
  const sortedList = Array.from(items).sort(function(a, b) {
    const c = a.textContent,
      d = b.textContent;
    return c < d ? -1 : c > d ? 1 : 0;
  });
  for (let item of sortedList) {
    frag.appendChild(item);
  }
  list.appendChild(frag);
})();
<ul>
  <li>Dogs</li>
  <li>Snakes</li>
  <li>Cats</li>
  <li>Bugs</li>
</ul>

Leave a Comment