temporarily removing and later reinserting a DOM element?

ajax, dom, javascript, jquery

Solution

You may use the `clone` method:

var els = $('.els'), saved = els.clone (true);
els.remove ();
// .... do other stuff
saved.appendTo ($('.wherever-you-want-to'));

That said, though, it's better to show & hide them (via `display: none`, for example), than to manipulate the DOM as it's very expensive. If you have to, use DOM insertion & removal (as above), rather than `.html ()`, which recreated a node from the given string every time.

Problem

Is there some jquery magic that will let me do the following: [0- define some element in HTML (eg, a unchecked checkbox)] 1- update its DOM element by setting one of its attributes using .attr() (eg, by setting its "checked" attribute using .attr('checked', true) ) 2- temporarily remove that element from the DOM 3- reinsert the original element into the DOM, while preserving all its properties (ie, so that it is checked as it was at the end of step 1-- NOT like it was when initially defined in the HTML) The reason why I am interested in removing these elements from the DOM (rather than hiding them) is that I have noticed that it seems to improve performance a good bit. My page has three different "states" and only a third of the total number of DOM elements is needed in any given state. [I wish to keep it as a single page with different states rather than breaking it into three separate pages.] Until now I had been removing and reinserting elements into the DOM by storing in a var the value of ``` $("#myElement").html() ``` and then removing it, but now I noticed that upon reinsertion of that HTML into the DOM the changes made [in step 1] had been "undone". Is there a way to do this -- to temporarily remove unneeded stuff from the DOM in a way that preserves all its properties for later reinsertion? thanks for any insight, lara

Original source

Related problems