Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - sorting a collection of divs

I am trying to learn Javascript alone so please don't suggest 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 example:

<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 cannot find a straight answer to what's wrong with this. Does getElementsByClassName return an array of the values of each div with that name? How, when the array is then sorted, so I reflect the changes in the divs?

like image 531
user2450099 Avatar asked Jun 04 '13 03:06

user2450099


People also ask

How do I sort a div element?

You can just get a reference to all of the divs you want to sort, then use JavaScript's native . sort() function.

Can you sort a set JavaScript?

Convert the Set into an array, using the Array. from() method. Sort the array, by using the Array.

How do I arrange numbers in ascending order in JavaScript?

JavaScript Array sort() The sort() sorts the elements as strings in alphabetical and ascending order.


1 Answers

You can't use the sort() function on a NodeList, which is what you are actually getting by calling getElementsByClassName or querySelectorAll.

So you'll have to convert it to an array before using Array.sort():

// Get elements and convert to array
const elems = [...document.querySelectorAll(".num")];

// Sort elements in-place
elems.sort((a, b) => Number(a.innerText) - Number(b.innerText));

// Join the array back into HTML
const outputHtml = elems.reduce((a, el) => a + el.outerHTML, "");

// Append HTML to parent container
document.getElementById('myDiv').innerHTML = outputHtml;

http://jsfiddle.net/g918jmoL/

like image 93
Samuel Liew Avatar answered Sep 28 '22 09:09

Samuel Liew