-
-
Save muthu32/dbbfb7f23fac79b4198dc0d65bb3d8b3 to your computer and use it in GitHub Desktop.
Swap two dom elements using jQuery
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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