Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to sort DOM nodes?

Tags:

javascript

dom

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> 
like image 410
James Avatar asked Nov 12 '08 00:11

James


People also ask

How many DOM nodes is too many?

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.

How are DOM nodes structured?

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.

How do I select a node in DOM?

The most common methods for selecting/creating a list of nodes in an HTML document are: querySelectorAll() getElementsByTagName() getElementsByClassName()

How do I sort in node JS?

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.


1 Answers

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]); } 
like image 80
nickf Avatar answered Sep 24 '22 05:09

nickf