Reputation: 11545
I was wondering what's the recommended way of storing inactive HTML elements.
as HTML strings:
var box = $('.box');
this.prev_box = box.html();
box.remove();
/* later */
$('body').append(this.prev_box);
as objects:
this.prev_box = $('.box');
this.prev_box.detach();
/* later */
$('body').append(this.prev_box);
I know that in the first case I'd have to bind the event handlers again, but other than that is there anything else I should know? Would it consume less memory than then 2nd method?
Upvotes: 1
Views: 191
Reputation: 3485
When considering which option is best for you, you need to think about why you are concerned about memory. Are you already seeing memory failures? Are you keeping track of so many elements that you know there will be memory issues? If these don't apply because you're storing just a handful of elements, then consider an option that keeps the code simple rather than something more complex.
There's three ways you can "store" dom elements. Each has pros/cons. I'll briefly touch on each:
As element object
This is what you show in your first example. The benefit of this is it maintains nearly all internal state (classes, styles, event listeners, etc.) which makes is very easy to add back into the live dom. Since it is already a dom element, adding it back in is also relatively efficient since it is in the browser's native format.
The downside is that it can take up a decent amount of memory (references to properties and other internal state).
As string representation
This is your second example. This also maintains class names and styles that you might have dynamically added.
Downside is that it also takes up a decent amount of memory because it contains string representation of all the properties that have been set (classes, styles, id, etc.). It is also less efficient to restore since the browser needs to parse it back into the dom element.
Custom state representation
I'd only recommend choosing this option in extreme cases, such as storing thousands of elements.
In this case, you write custom code to store just differences from the base element, such as classes or styles that have been added or removed. In other words, just the minimal amount of information necessary to restore the element to its previous state. The benefit is that you can tweak it to use the least amount of memory to store and restore an element.
The downside is that it adds significant code complexity.
Upvotes: 1