Javascript - sorting a collection of divs

I am trying to learn Javascript myself, so please do not offer a library or jQuery.

I have a list of divs and I want the user to be able to sort them by their value. For instance:

<button onclick="sort();">Test</button> <div class="num">2</div> <div class="num">3</div> <div class="num">8</div> <div class="num">1</div> 

JS:

 function sort(){ var elements = document.getElementsByClassName("num"); elements.sort(); } 

I can not find a direct answer to what is wrong with this. Does getElementsByClassName return an array of values ​​for each div with that name? How when the array is sorted, so I reflect the changes in the divs?

+4
source share
3 answers

You cannot use the sort() function in a NodeList, which is what you actually get by calling getElementsByClassName

 var elems = document.getElementsByClassName("num"); // convert nodelist to array var array = []; for (var i = elems.length >>> 0; i--;) { array[i] = elems[i]; } // perform sort array.sort(function(a, b) { return Number(a.innerHTML) - Number(b.innerHTML); }); // join the array back into HTML var output = ""; for (var i = 0; i < array.length; i++) { output += array[i].outerHTML; } // append output to div 'myDiv' document.getElementById('myDiv').innerHTML = output; 

http://jsfiddle.net/UydrZ/7/

Of course, if you use jQuery for this, it will be easier. See jQuery - Sorting div content

+5
source

The problem is that getElementsByClassName returns a nodeList , not an array. Well, I have to say that this is very stupid, and I still can’t understand why the browser implemented it that way ...

What you can do, but first convert the nodeList to an array, and then sort:

 var elems = Array.prototype.slice.call(elements); elems.sort(/* function (a, b) {} */); 

Note that the sort function is optional and is usually passed after the first value. (Although, called directly in your list of elements, .sort() will not sort anything without a function parameter, since it will not know which one will be presented before the other)

Make an MDN call application to understand how it really works behind the scenes: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call

0
source

Sorting nodes is not so simple, you may have to deal with other nodes that may interfere. Anyway, here is a function that takes a NodeList or HTMLCollection, converts it into an array, sorts it, then returns the nodes in order. Note that the elements are placed at the bottom of the parent element, so all other elements will be located at the top. In any case, it demonstrates an approach that you can adapt.

There are many other approaches, including others using DOM methods, beware of any based on markup markup. Also, beware of cloning elements, as this may have unwanted side effects for listeners (they may or may not be removed, depending on the browser and how they were added).

 <script type="text/javascript"> function getText(el) { return el.textContent || el.innerText || ''; } function sortElements(nodeList) { // Assume there a common parent var node, parentNode = nodeList[0].parentNode // Define a sort function function sortEls(a, b) { var aText = getText(a); var bText = getText(b); return aText == bText? 0 : aText < bText? -1 : 1; } // Convert nodelist to an array and remove from the DOM at the same time var a = [], i = nodeList.length; while (i--) { a[i] = parentNode.removeChild(nodeList[i]); } // Sort the array a.sort(sortEls); // Put elements back in order i = 0; while (node = a[i++]) { parentNode.appendChild(node); } } </script> <div>0</div> <div>4</div> <div>2</div> <div>3</div> <div>5</div> <button onclick="sortElements(document.getElementsByTagName('div'))">Sort</button> 
0
source

Source: https://habr.com/ru/post/1484328/


All Articles