-
Notifications
You must be signed in to change notification settings - Fork 7
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.
-
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>
-
Define this function
function sortElementChildren (el, sortOptions) { sortArray([...el.children], sortOptions).map(child => el.appendChild(child)) }
-
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' })