Skip to content

Instantly share code, notes, and snippets.

@muthu32
Forked from derek-dchu/jQuery_swap_elements
Last active June 7, 2021 07:25
Show Gist options
  • Save muthu32/dbbfb7f23fac79b4198dc0d65bb3d8b3 to your computer and use it in GitHub Desktop.
Save muthu32/dbbfb7f23fac79b4198dc0d65bb3d8b3 to your computer and use it in GitHub Desktop.
Swap two dom elements using jQuery
function swapNodes(a, b) {
var aparent = a.parentNode;
var asibling = a.nextSibling === b ? a : a.nextSibling;
b.parentNode.insertBefore(a, b);
aparent.insertBefore(b, asibling);
}
/** USING JQUERY ***/
function swaptwoID(a,b) {
var nextID = $('#'+a).next().prop('id');
nextID= nextID==b?a:nextID;
$('#'+a).insertBefore($('#'+b));
$('#'+b).insertBefore($('#'+nextID));
}
/**
* Swap two elements within a multiple selector with index a and b
* @param a: index of the first element
* @param b: index of the second elemnt
*
* DEMO at http://jsfiddle.net/derekhu/8rauhuxh/#base
*/
function swapElement(elements, indexA, indexB) {
// Make sure indexA is smaller than indexB
if (indexA > indexB) {
indexA = indexB + (indexB = indexA, 0);
}
var a = elements.get(indexA);
var b = elements.get(indexB);
$(a).insertAfter(b);
$(b).insertBefore(elements.get(indexA + 1));
}
/**
* Swap two dom elements
* @param a: a single element selector of the first element
* @param b: a single element selector of the second element
*
* DEMO at http://jsfiddle.net/derekhu/pr53m04n/#base
*/
function swapElement(a, b) {
// create a temporary marker div
var aNext = $('<div>').insertAfter(a);
a.insertAfter(b);
b.insertBefore(aNext);
// remove marker div
aNext.remove();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment