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?
You can just get a reference to all of the divs you want to sort, then use JavaScript's native . sort() function.
Convert the Set into an array, using the Array. from() method. Sort the array, by using the Array.
JavaScript Array sort() The sort() sorts the elements as strings in alphabetical and ascending order.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With