Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

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

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..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...