Hice un script para ordenar (A a Z)
Mi pregunta es qué debo agregar a esto para tener la función de desclasificación, quiero decir, establecerla por defecto ( cómo estaba antes de ordenarlos ).
Código:
function sortList() { document.getElementById('sortedtxt').innerHTML = 'Sorted A-Z'; document.getElementById('sortedtitle').innerHTML = 'BFMAS - Sorted A-Z'; var list, i, switching, b, shouldSwitch; list = document.getElementById("sortingUL"); switching = true; while (switching) { switching = false; b = list.getElementsByTagName("LI"); for (i = 0; i < (b.length - 1); i++) { shouldSwitch = false; if (b[i].innerHTML.toLowerCase() > b[i + 1].innerHTML.toLowerCase()) { shouldSwitch = true; break; } } if (shouldSwitch) { b[i].parentNode.insertBefore(b[i + 1], b[i]); switching = true; } } }Utilice este código JS y HTML
let globalList, temp = [], sorted = true; document.getElementById("sort").addEventListener('click', sortList); document.getElementById("unsorted").addEventListener('click', UnsortedList); function UnsortedList() { let currentList = document.getElementById("countries"); currentList.innerHTML = ''; temp.forEach(function (item) { let li = document.createElement('li'); currentList.appendChild(li); li.innerHTML += item; }); sorted = true; } function getTempArray(pList) { globalList = pList.getElementsByTagName("li"); temp = []; for (let j = 0; j < globalList.length; j++) { temp.push(globalList[j].innerText); } } function sortList() { let list, i, switching, b, shouldSwitch; list = document.getElementById("countries"); if (sorted === true) { getTempArray(list); sorted = false; } switching = true; while (switching) { switching = false; b = list.getElementsByTagName("li"); for (i = 0; i < (b.length - 1); i++) { shouldSwitch = false; if (b[i].innerHTML.toLowerCase() > b[i + 1].innerHTML.toLowerCase()) { shouldSwitch = true; break; } } if (shouldSwitch) { b[i].parentNode.insertBefore(b[i + 1], b[i]); switching = true; } } }<!DOCTYPE html> <html lang="es"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <title>Pues </title> </head> <body> <p>Click the button to sort the list alphabetically 🙂</p> <button id="sort"><b>Sort</b></button> <button id="unsorted"><i>Unsorted</i></button> <ul id="countries"> <li>Peru</li> <li>Argentina</li> <li>Brazil</li> <li>Colombia</li> <li>Paraguay</li> <li>Bolivia</li> </ul> </body> </html>
En primer lugar, parece una locura que esté ordenando los elementos del DOM in situ (en su lugar), en lugar de tener una estructura de datos de lista separada (por ejemplo, una matriz) y tratar el DOM como una vista... es decir, representar los datos de la lista en el DOM según sea necesario (es decir, después de que se actualice o después de ordenarlo).
Recomendación:
sortedtxt a una matriz.<ul> , <ol> o <table> apropiado.Beneficios: