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

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-28 07:08:40

问题


I need to sort out the elements that are already displayed in ascending order so that they just rearrange. I need to sort them out by the values in their data-val attributes.

<div id="a" class="item" data-val="6">Item a</div>
<div id="b" class="item" data-val="8">Item b</div>
<div id="c" class="item" data-val="2">Item c</div>
<div id="d" class="item" data-val="5">Item d</div>

<br />
<button onclick="sortOut()">Sort Out</button> 

I made an example here: http://jsfiddle.net/quatzael/uKnpa/

I dont know how to do that. I kind of started but it is probably wrong.

I need the function to firstly find out what elements have class called "item" and then those with this class sort out by the value of their data-val attribute.

It has to work in all browsers so the solution should probably involve .appendChild()

Tnx for any help..


回答1:


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.



来源:https://stackoverflow.com/questions/14131008/how-to-sort-out-elements-by-their-value-in-data-attribute-using-js

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