Skip to content

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

Lloyd Brookes edited this page Oct 26, 2019 · 8 revisions
  1. Load sort-array

    a. From an ECMAScript Module

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

    b. The old-fashioned way

    import sortArray from './node_modules/sort-array/dist/index.mjs'
    
  2. Define this function

    function sortElementChildren (el, sortOptions) {
      sortArray([...el.children], sortOptions).map(child => el.appendChild(child))
    }
  3. Sort a DOM elements children

    sortElementChildren($('ul'), {
      by: 'textContent',
      order: 'desc'
    })
    

Clone this wiki locally