You need to append them to the DOM in the newly sorted order.
Here's what I added to your code to do this:
divs.sort(function(a, b) {
return a.dataset.val.localeCompare(b.dataset.val);
});
var br = document.getElementsByTagName("br")[0];
divs.forEach(function(el) {
document.body.insertBefore(el, br);
});
http://jsfiddle.net/RZ2K4/
The appendChild()
method could be used instead of .insertBefore()
if your sorted items were in a container with nothing else.
To support older browsers, you would use .getAttribute("data-val")
instead of .dataset.val
.
And if you want a numeric sorting, you shouldn't use .localeCompare
in the .sort()
function.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…