How to move or swap elements in jQuery?

html, jquery

Solution

/**
 * @param siblings {jQuery} List of sibling elements to act upon
 * @param subjectIndex {int} Index of the item to be moved
 * @param objectIndex {int} Index of the item to move subject after
 */
var swapElements = function(siblings, subjectIndex, objectIndex) {
    // Get subject jQuery
    var subject = $(siblings.get(subjectIndex));
    // Get object element
    var object = siblings.get(objectIndex);
    // Insert subject after object
    subject.insertAfter(object);
}
$(function() {
    swapElements($('li'), 0, 1);
});
​

Working example: http://jsfiddle.net/faceleg/FJt9X/2/

Problem

The goal is to move an element before its left sibling or after its right sibling. ``` <ul> <li>One</li> <li>Two</li> <li>Three</li> <li>One</li> </ul> ``` Given only the index of the element, I need to move it to left or right. Say the index is 1 (LI with "Two" as innerText), then I want to move it to left, the output should be: ``` <ul> <li>Two</li> <li>One</li> <li>Three</li> <li>One</li> </ul> ```

Original source