Classic "bubble" does not work - nodes are not assigned:

for(var i = 0; i < List.childElementCount; i++){ for(var j = List.childElementCount-1; j > i; j--){ if (parseInt(List.childNodes[j-1].id) > parseInt(List.childNodes[j].id)){ var Buf = List.childNodes[j-1]; List.childNodes[j-1] = List.childNodes[j]; List.childNodes[j] = Buf; } } } 

List

I tried List.replaceChild instead of assignment - in general the list is cleaned.

How to sort nodes by their numeric id?

PS: Changing by node attributes is not an option, you need objects entirely, since one of the elements can be selected (marked with another font-weight and color) - this should be preserved during sorting.

    2 answers 2

    You don’t correctly think that if you change the data in the childNodes - childNodes , then this will somehow affect the DOM-структуру . All need to do handles

     const list = document.getElementById('List') // функция сортировки const sortListById = (list) => { const listElements = [...list.children] // превращаем NodeList в настоящий массив // сортируем const sortedListElements = listElements.sort((a, b) => (+a.id) - (+b.id)) // очищаем родительский контейнер list.innerHTML = '' // вставляем элементы в новом порядке sortedListElements.forEach(el => list.appendChild(el)) } const button = document.querySelector('button') button.onclick = () => sortListById(list) 
     a { display: block; padding: 5px; } 
      <button>Сортировать</button> <div id='List'> <a id='9999' href='#'>9999</a> <a id='9998' href='#'>9998</a> <a id='7999' href='#'>7999</a> <a id='9591' href='#'>9591</a> <a id='1436' href='#'>1436</a> <a id='345' href='#'>345</a> </div> 

    UPDATE
    es5 syntax

     var list = document.getElementById('List') // функция сортировки var sortListById = function (list) { var listElements = Array.prototype.slice.call(list.children); // превращаем NodeList в настоящий массив // сортируем var sortedListElements = listElements.sort(function(a, b) { return (+a.id) - (+b.id); }) // очищаем родительский контейнер list.innerHTML = '' // вставляем элементы в новом порядке sortedListElements.forEach(function(el) { list.appendChild(el) }); } var button = document.querySelector('button'); button.onclick = function () { sortListById(list); } 
    • I do not know ... no matter how I assign the list of childNodes to a separate variable, after list.innerHTML = ''; the buffer list is also empty - Iceman
    • @Iceman, how exactly do you assign? Added code for old syntax - ThisMan
    • Thank you very much! UPDATE code works. Although I don’t understand why the first option didn’t work - launched in Chromium 58 - Iceman

     let arr = Array.from(document.querySelectorAll('a')), // собираем массив из элементов, которые надо упорядочить по айди parent = document.querySelector('div'); // контейнер, в котором находятся элементы while (parent.firstChild) { // очищаем контейнер от неупорядоченных элементов parent.removeChild(parent.firstChild); } arr.sort(function(a, b) { // сортируем массив элементов по атрибуту айди return parseFloat(a.id) - parseFloat(b.id); }) arr.forEach(function(item) { // вставляем массив в контейнер parent.appendChild(item); }); 
     a { display: block; } 
     <div> <a id="1" href="#">1</a> <a id="8" href="#">8</a> <a id="6" href="#">6</a> <a id="2" href="#">2</a> <a id="10" href="#">10</a> <a id="3" href="#">3</a> </div> 

    • cleaning could be done immediately as parent.innerHTML = '' , there are no extra iterations))) - Vasily Barbashev
    • @ Vasily Barbashev himself did not check, but they write that through .innerHTML = '' clean up longer." - Sasha Omelchenko
    • how can it be longer when your time grows on the number of elements in the cycle. And here you just say erase everything inside :) At the same time, if you work with removeChild and have a saved reference to the DOM element, and then delete it, the link will remain, i.e. will not be removed from memory, it means it will occupy it. It's simple :) Your option is also correct. - Vasily Barbashev
    • @ Vasily Barbashev speed check can be viewed here: jsperf.com/innerhtml-vs-removechild - Sasha Omelchenko