Optimize “layering” in jQuery I am building an web application that is going to work in a similar way like photoshop or illustrator regarding layers. Here are my code that is searching the ".case" div for images, and then put these images id's to an array. When that is done we are looping the array to find out if the received image is the same as the one we loop through from the array.

When finding this image we wan't to move it one step up or down in the hierarchy. But this image have a div with controllers associated, so we have to move this in the same way.

So do you think this is the best possible code we can create to get this work? It does work, I only want to find out if there are any better solutions for it.

var arrangeLayers = function(e,direction) {

    var timestampId = e.attr('id');
        timestampId = timestampId.replace('name', '');

    var elem = [];
    $('.case img').each(function(){
        elem.push($(this).attr('id'));
    });

    for (i=0;i&lt;elem.length;i++) {
        if (timestampId == elem[i] &amp;&amp; direction == 'down') {            
            if (i != 0) {
                $('#' + timestampId).insertBefore($('#' + elem[(i-1)]));    
                $('#name' + timestampId).insertBefore($('#' + timestampId));    
            }
        } else if (timestampId == elem[i] &amp;&amp; direction == 'up') {
            if (i != (elem.length) -1) {
                $('#' + timestampId).insertAfter($('#' + elem[(i+1)])); 
                $('#name' + timestampId).insertBefore($('#' + timestampId));
            }
        }
    }
}
Not if I understand what you're doing correctly.

So essentially each image has itself, and then some other element that should be before it as a buddy? Assuming they are all siblings, you should utilize some of jQuery's functions that support working with siblings.

Here's an example, though I'm sure it could still be better:

var arrangeLayers = function (e, direction) {
    var $target = $(e);
    var $targetBuddy = $target.prev();
    if (direction === 'down') {     
        if($targetBuddy.index() &gt; 1) {
            $target.insertBefore($targetBuddy.prev().prev());
        }
    } else {
        if ($target.index() !=$target.siblings().length) {
            $target.insertAfter($target.next().next());
        }
    }
    $targetBuddy.insertBefore($target);
}


Or if you don't care about index error checking (which in actual practice appears to not matter):

var arrangeLayers = function (e, direction) {
    var $target = $(e);
    var $targetBuddy = $target.prev();
    if (direction === 'down') {     
        $target.insertBefore($targetBuddy.prev().prev());
    } else {
        $target.insertAfter($target.next().next());
    }
    $targetBuddy.insertBefore($target);
}


Here's a jsfiddle without the checking: