Search code examples
javascriptsortingappendchild

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


Solution

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