How to sort out elements by their value in data- attribute using JS

筅森魡賤 提交于 2019-11-28 02:23:52

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!