0

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?

1

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @Matt ! but a little question with the logic. Why do we subtract a's sequence to b's sequence?
@AJ: the sort function must return < 0 if "a" is to be earlier than "b" in the sort order, 0 if they're equal, and > 1 if "a" should be after "b". The "-" is a easy way to do that if the sort value is a number.
1

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.