jQuery 1.4 has a very helpful function ‘detach’ where I can detach a section and keep it away for later use. The best part is that it keeps all my bindings intact. But like anything else you need to watch out for caveats.
Consider the following example:
$(document).ready(function (){ //detach and keep the reference var $a = $('#div-abcde').detach(); //try to change the value of one of the detached elements $('#abcde').val('5678'); //attach it back $('#div-abcd').after($a); //output alert($('#abcde').val()); });
<form id = "grid-3762" name = "grid" action = ""> <div id="div-abcd"><input type="text" id="abcd" class="abcd" value="abcd" /> </div> <div id="div-abcde"><input type="text" id="abcde" class="abcd" value="abcde" /> </div> </form>
This works as expected. The statement ‘$(‘#abcde’).val(‘5678′);’ has no effect as this element has been detached. So the output is as expected, that is ‘abcde’.
Now lets do the same example a little differently. Consider this:
$(document).ready(function (){ //keep a reference to the element. //remember this element wil be part of the detach var $r = $('#abcde'); //detach and keep the reference var $a = $('#div-abcde').detach(); //try to change the value using the reference $r.val('5678'); //attach it back $('#div-abcd').after($a); //output alert($('#abcde').val()); });
So what we are doing here that we are changing the value of the element by using a reference to the element. This is reference $r to the element.
Now the output is ‘5678’!
So even though it is detached it still maintains its references.