Skip to content

Instantly share code, notes, and snippets.

@narainsagar
Last active October 8, 2016 23:33
Show Gist options
  • Save narainsagar/50445f30b065a66b4acf to your computer and use it in GitHub Desktop.
Save narainsagar/50445f30b065a66b4acf to your computer and use it in GitHub Desktop.
Swap two DOM elements using jQuery (Events and a possible focus or Bindings wouldn't be lost during/after swapping!)
/* A very simple and nice function to swap DOM elements */
// Solution #1
function swap($elementA, $elementB) {
var temp = $('<div>').insertAfter($elementA);
$elementA.insertAfter($elementB);
$elementB.insertBefore(temp);
temp.remove();
}
var $elemA = $('#input_field_1'); /* from: provide the first field id / class. */
var $elemB = $('#input_field_2'); /* to: provide the second field id / class. */
swap($elemA, $elemB); /* call to function for swapping. */
// Solution #2
function swap(id1, id2) { // id with hash i.e., ('#input_field_1', '#input_field_2')
function parentFor($el) {
return $el.closest('.left, .right').wrapInner('<div class="switch" />');
// .left and .right id1 & id2 parent div's classes, .left is of id1 and .right is of id2
}
var container1 = parentFor($(id1));
var container2 = parentFor($(id2));
container1.prepend(container2.find('.switch'));
container2.prepend(container1.find('.switch:nth-child(2)'));
}
// Creator: Narain Sagar (Nine)
// Created: 11-09-2015
// Cheers!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment