Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
167
rated 0 times [  168] [ 1]  / answers: 1 / hits: 20206  / 15 Years ago, fri, january 8, 2010, 12:00:00

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


More From » jquery

 Answers
103

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.


[#97890] Tuesday, January 5, 2010, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
elijahm

Total Points: 674
Total Questions: 124
Total Answers: 79

Location: Northern Mariana Islands
Member since Fri, Jan 15, 2021
3 Years ago
;