Skip to content

Instantly share code, notes, and snippets.

@joyeecheung
Last active August 29, 2015 14:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joyeecheung/422555fd4d6f4d61dc9d to your computer and use it in GitHub Desktop.
Save joyeecheung/422555fd4d6f4d61dc9d to your computer and use it in GitHub Desktop.
Reverse the children of an DOM Element while preserving their CSS styles and event listeners. Due to their incorrect implementation of `children`, this might no work in IE8-.
function reverseChild(pare) {
if (!pare.children || pare.children.length < 2) return;
var emptyParent = document.createElement(pare.nodeName);
var detachedParent = pare.parentNode.replaceChild(emptyParent, pare);
var emptyLeft = document.createElement(detachedParent.children[0].nodeName);
var emptyRight = document.createElement(detachedParent.children[0].nodeName);
for (var i = 0, len = detachedParent.children.length; i < Math.floor(len/2); i++) {
var left = detachedParent.replaceChild(emptyLeft, detachedParent.children[i]);
var right = detachedParent.replaceChild(emptyRight, detachedParent.children[len - i - 1]);
emptyleft = detachedParent.replaceChild(right, emptyLeft);
emptyright = detachedParent.replaceChild(left, emptyRight);
}
emptyParent.parentNode.replaceChild(detachedParent, emptyParent);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment