Skip to content

Instantly share code, notes, and snippets.

@derek-dchu
Last active December 12, 2023 20:17
Show Gist options
  • Save derek-dchu/8c828fc40b17646cbb78 to your computer and use it in GitHub Desktop.
Save derek-dchu/8c828fc40b17646cbb78 to your computer and use it in GitHub Desktop.
Swap two dom elements using jQuery
/**
* 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();
}
@LeonGtHWeb
Copy link

ok

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment