Skip to content

Instantly share code, notes, and snippets.

@techsin
Created October 23, 2020 02:15
Show Gist options
  • Save techsin/8968dfff18d68d940fb72c05139d1476 to your computer and use it in GitHub Desktop.
Save techsin/8968dfff18d68d940fb72c05139d1476 to your computer and use it in GitHub Desktop.
Sort Html Elements
// $container - css selector for nodes that need to be sorted
// $number - css selector for node with number
function sortElements($container, $number) {
const hash = new Map();
const list = Array.from(document.querySelectorAll($container));
for (let i = 0; i < list.length; i++) {
for (let j = i; j < list.length; j++) {
const element = list[i];
const element2 = list[j];
if (getNum(element) < getNum(element2)) {
swapEle(element, element2);
const t = list[i];
list[i] = list[j];
list[j] = t;
}
}
}
function swapEle(a, b) {
const a_next = a.nextElementSibling;
const b_next = b.nextElementSibling;
const a_parent = a.parentElement;
const b_parent = b.parentElement;
// parentNode.insertBefore(newNode, referenceNode)
// referenceNode The node before which newNode is inserted. If this is null, then newNode is inserted at the end of parentNode's child nodes.
if (b_next !== a) {
b_parent.insertBefore(a, b_next);
}
if (a_next !== b) {
a_parent.insertBefore(b, a_next);
}
}
function getNum(ele) {
if (hash.get(ele) === undefined) {
const str = ele.querySelector($number)?.innerText || '';
hash.set(ele, parseFloat(str.replace(/[^0-9.-]+/g, "")) || 0);
}
return hash.get(ele);
}
}
sortElements('','');
// insertAdjacentElement beforebegin
// insertAdjacentElement afterend
// insertBefore
// Node.nextSibling for insertAfter
// Node.previousSibling
// previousElementSibling
// nextElementSibling
// ChildNode.replaceWith()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment