48 lines
1.2 KiB
JavaScript
48 lines
1.2 KiB
JavaScript
// sortLists.js
|
|
|
|
// Function to detect if a string contains numbers
|
|
function extractNumber(text) {
|
|
const match = text.match(/\d+/);
|
|
return match ? parseInt(match[0], 10) : null;
|
|
}
|
|
|
|
// Sorting function
|
|
function sortListItems(a, b) {
|
|
const textA = a.textContent.trim().toLowerCase();
|
|
const textB = b.textContent.trim().toLowerCase();
|
|
|
|
const numA = extractNumber(textA);
|
|
const numB = extractNumber(textB);
|
|
|
|
if (numA !== null && numB !== null) {
|
|
// Both contain numbers -> sort numerically
|
|
if (numA !== numB) return numA - numB;
|
|
return textA.localeCompare(textB);
|
|
}
|
|
|
|
if (numA !== null) {
|
|
// A has number, B doesn't -> numbers first
|
|
return -1;
|
|
}
|
|
if (numB !== null) {
|
|
// B has number, A doesn't
|
|
return 1;
|
|
}
|
|
|
|
// Otherwise sort alphabetically
|
|
return textA.localeCompare(textB);
|
|
}
|
|
|
|
// Main function to sort all ULs
|
|
function sortAllULs() {
|
|
const uls = document.querySelectorAll("ul");
|
|
uls.forEach(ul => {
|
|
const items = Array.from(ul.querySelectorAll("li"));
|
|
items.sort(sortListItems);
|
|
items.forEach(item => ul.appendChild(item)); // reattach in sorted order
|
|
});
|
|
}
|
|
|
|
// Run after page load
|
|
document.addEventListener("DOMContentLoaded", sortAllULs);
|