If I have a list like this:
<ul id="mylist"> <li id="list-item1">text 1</li> <li id="list-item2">text 2</li> <li id="list-item3">text 3</li> <li id="list-item4">text 4</li> </ul>
What's the easiest way to re-arrange the DOM nodes to my preference? (This needs to happen automatically when the page loads, the list-order preference is gained from a cookie)
E.g.
<ul id="mylist"> <li id="list-item3">text 3</li> <li id="list-item4">text 4</li> <li id="list-item2">text 2</li> <li id="list-item1">text 1</li> </ul>
A parent node with greater than 60 child nodes exists. The “avoid excessive DOM size” warning doesn't directly affect any Lighthouse metrics. While in theory, pages with a large DOM can load fast but in the real world, they mostly don't.
The DOM consists of a tree structure of nested nodes, which is often referred to as the DOM tree. You may be familiar with an ancestral family tree, which consists of parents, children, and siblings.
The most common methods for selecting/creating a list of nodes in an HTML document are: querySelectorAll() getElementsByTagName() getElementsByClassName()
Use the sort() method to sort the result in ascending or descending order. The sort() method takes one parameter, an object defining the sorting order.
Though there's probably an easier way to do this using a JS Library, here's a working solution using vanilla js.
var list = document.getElementById('mylist'); var items = list.childNodes; var itemsArr = []; for (var i in items) { if (items[i].nodeType == 1) { // get rid of the whitespace text nodes itemsArr.push(items[i]); } } itemsArr.sort(function(a, b) { return a.innerHTML == b.innerHTML ? 0 : (a.innerHTML > b.innerHTML ? 1 : -1); }); for (i = 0; i < itemsArr.length; ++i) { list.appendChild(itemsArr[i]); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With