AJ Naidas
AJ Naidas

Reputation: 1424

Best way to sort elements by an integer value through javascript

I have elements ordered like this :

<div class="item pix-txt medium">
   <span class="animated jumbo bold" data-sequence="5" data-entrance="fade" data-exit="fade" data-top="50" data-left="-150">Masters of the Internet</span> 
   <span class="animated medium" data-sequence="3" data-entrance="fade" data-exit="fade">
   <span class="animated medium" data-sequence="2" data-entrance="fade" data-exit="fade"></span>

</div>

Each .animated span has a data-sequence with an integer attached to it. What is the best way to sort these elements in a javascript Array by data-sequence value?

Upvotes: 0

Views: 280

Answers (2)

Dogbert
Dogbert

Reputation: 222198

Here's a pure JS solution. You may have to adjust the selector part to your needs.

function sortElementsByAttribute(selector, attribute) {
    // Fetch all elements matching the selector, and convert it to an Array from a NodeList
    var elements = [].slice.call(document.querySelectorAll(selector));

    // `sort` sorts inplace
    elements.sort(function (n1, n2) {
        // convert `attribute` attribute to integers, and sort the elements by that.
        return parseInt(n1.getAttribute(attribute), 10) - parseInt(n2.getAttribute(attribute), 10);
    });

    // Loop through the sorted elements
    for (var i = 0; i < elements.length; i++) {
        var node = elements[i];
        // This would move the `node` to be the last child of its parent node,
        // basically sorting the elements
        node.parentNode.appendChild(node);
    }
}

sortElementsByAttribute(".item span", "data-sequence");

http://jsfiddle.net/QssyK/

Upvotes: 1

Matt
Matt

Reputation: 75317

If you want to sort them in a JavaScript array, but not sort the DOM, you can do this;

var ar = $('.item').children().get().sort(function (a, b) {
    return $(a).data('sequence') - $(b).data('sequence');
});

This turns the jQuery object into an Array using get(), and then uses the Array sort() function.

Note ar will be a JavaScript array, not a jQuery object.

Upvotes: 1

Related Questions