Dutchie432
Dutchie432

Reputation: 29160

jQuery: Sorting Divs Based on their ID, Based to ID List

If have an array of Javascript IDs

var myArray = ['2', '1', '3'];

Now, I also have a group of DIVS with corresponding ID.

<div id='container'>
   <div id='item1'>1</div>
   <div id='item2'>2</div>
   <div id='item3'>3</div>
</div>

Is there an easy way to sort these divs based on the array order? I have bounced around the idea of just looping through the divs and using insertBefore() and insertAfter() to re-arrange the items, but I am wondering if there is a better way..

This is what I've come up with so far (JSFiddle DEMO)

(function( $ ){
    $.fn.jaySort= function(prefix, lst) {
        var prev=null;
        for (var x=0; x<lst.length; x++){
            if (!prev) prev = $('#placeHolder');
            $('#' + prefix + lst[x]).insertAfter(prev);
            prev = $('#' + prefix + lst[x]);
        }
    };
})( jQuery );  


///////////////////////////////////////////

var myArray = ['2', '1', '3'];
$('#container').jaySort('item', myArray);

UPDATE

Based on the accepted answer below, the code has been refined to:

(function( $ ){
    $.fn.jaySort= function(prefix, lst) {
        for (var x=0; x<lst.length; x++)
            $(this).append($('#' + prefix + lst[x]));
    };
})( jQuery );  
$('#container').jaySort('item', ['3', '2', '1']);

Upvotes: 2

Views: 2706

Answers (1)

Can&#39;t Tell
Can&#39;t Tell

Reputation: 13426

This also works(and is shorter)

<div id='container'>
   <div id='item1'>1</div>
   <div id='item2'>2</div>
   <div id='item3'>3</div>
</div>

var myArray = ['2', '1', '3'];

$.each(myArray,function(index,value){
   $('#container').append($('#item'+value));
});

jsFiddle

Upvotes: 6

Related Questions