Created
April 23, 2011 16:43
-
-
Save cowboy/938767 to your computer and use it in GitHub Desktop.
JavaScript detach: detach a node from the DOM, optionally reattaching it when done.
This file contains 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
/*! | |
* JavaScript detach - v0.2 - 5/18/2011 | |
* http://benalman.com/ | |
* | |
* Copyright (c) 2011 "Cowboy" Ben Alman | |
* Dual licensed under the MIT and GPL licenses. | |
* http://benalman.com/about/license/ | |
*/ | |
function detach(node, async, fn) { | |
var parent = node.parentNode; | |
var next = node.nextSibling; | |
// No parent node? Abort! | |
if (!parent) { return; } | |
// Detach node from DOM. | |
parent.removeChild(node); | |
// Handle case where optional `async` argument is omitted. | |
if (typeof async !== "boolean") { | |
fn = async; | |
async = false; | |
} | |
// Note that if a function wasn't passed, the node won't be re-attached! | |
if (fn && async) { | |
// If async == true, reattach must be called manually. | |
fn.call(node, reattach); | |
} else if (fn) { | |
// If async != true, reattach will happen automatically. | |
fn.call(node); | |
reattach(); | |
} | |
// Re-attach node to DOM. | |
function reattach() { | |
parent.insertBefore(node, next); | |
} | |
} |
This file contains 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
// Get an element. | |
var elem = document.getElementById('huge-ass-table'); | |
// Just detach element from the DOM. | |
detach(elem); | |
// Detach + exec fn + reattach, synchronous. | |
detach(elem, function() { | |
// this == elem, do stuff here. | |
}); | |
// Detach + exec fn + reattach, asynchronous. | |
detach(elem, true, function(reattach) { | |
// this == elem, do stuff here, call reattach() when done! | |
setTimeout(reattach, 1000); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I recommend using this function for save use:
nice idea, thanks for sharing