Skip to content

How to sort a list of DOM elements in an HTML document

Lloyd Brookes edited this page May 15, 2021 · 8 revisions

This example sorts a DOM element's children in-place. It is fast and doesn't destroy the state (e.g. whether an <option> element is selected or not) of items being sorted.

  1. In your web application, load sort-array.

    a. Import the ECMAScript Module.

    import sortArray from './node_modules/sort-array/dist/index.mjs'

    b. The old-fashioned way (adds window.sortArray).

    <script nomodule src="./node_modules/sort-array/dist/index.js"></script>
  2. Define this function

    function sortElementChildren (el, sortOptions) {
      sortArray([...el.children], sortOptions).map(child => el.appendChild(child))
    }
  3. Sort a DOM element's children, for example the <li> children of a <ul> element.

    const ul = document.querySelector('ul')
    sortElementChildren(ul, {
      by: 'textContent',
      order: 'desc'
    })
Clone this wiki locally