Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move or swap elements in jQuery?

Tags:

html

jquery

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>
like image 721
dpp Avatar asked Aug 09 '12 05:08

dpp


3 Answers

If you need an element to be moved left or right, there are jQuery methods like next and prev to help you get the next and previous elements where you can apply insertAfter or insertBefore.

//Move right:
$(elementToBeMoved).insertAfter($(elementToBeMoved).next());

//Move left:
$(elementToBeMoved).insertBefore($(elementToBeMoved).prev());
like image 122
dpp Avatar answered Oct 19 '22 23:10

dpp


/**
 * @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/

like image 37
Michael Robinson Avatar answered Oct 20 '22 01:10

Michael Robinson


I've made a jquery extension that's easy to use

jQuery.fn.swap = function (newIndex) {
    if (!Number.isInteger(newIndex) && !['up', 'down'].includes(newIndex)) {
        throw new Error('Incorrect index format! Allowed formats are: "up", "down" or an index of the sibling to swap with');
    }
    if (Number.isInteger(newIndex)) {
        this.insertBefore(this.siblings()[newIndex]);
    } else {
        if (newIndex === 'up') {
            this.insertBefore($(this.siblings()[this.index() - 1]));
        } else {
            this.insertAfter($(this.siblings()[this.index()]));
        }
    }
}

After including above sample this script can be used on jquery objects like:

$(this).swap('up');
$(this).swap('down');
$(this).swap(1);
like image 39
Henk Kuchelvork Avatar answered Oct 20 '22 01:10

Henk Kuchelvork