0

Let's say before my webapp starts, I want to create all dom elements initially and store them in some preloaded array. Something like:

for (i = 1...100) { preLoader.push($('<div id="' + i + '" />')); }

and then later, depending on the action, I will take the correct element from the array and append it to the DOM.
Now my question is: if I were to later do:

$(div#i).remove()

will it also affect my preLoader array, or is it a different reference than the one in the DOM?

0

2 Answers 2

2

will it also affect my preLoader array

No, it will not. Object will be removed from memory, only and only if there are no ways to access it, that is no references to it. After $('div#'+i).remove(), you can't access it from the DOM, but you can still access it by preLoader[i-1].So you need to remove the object from preLoader array explicitly:

preLoader.splice(i-1,1);
Sign up to request clarification or add additional context in comments.

3 Comments

I thought all DOM-related functions (like append) actually take the argument and create a new object in memory for it just for the DOM and then attach it? So that, for example, if after appending to the DOM I do: $('div#'+i).css(width:0), it would only apply it to the element in the DOM, not the one stored in my array since they're different entities. Or do they actually point to the same address in memory and therefore modifying one, would modify the other as well?
@paulsmith Look, jQuery is just a mechanism for easy-working with DOM. In reality there is only DOM and DOMElements . So when you are removing DOMElement from DOM (no metter by using jQuery or smthn else), they won't be removed from jQuery wrappers,that are existed in your preLoader array, and which holds references to appropriate DOMElement.
@paulsmith, answering your question: "$('div#'+i).css(width:0), it would only apply it to the element in the DOM". No, it will apply for the elements in your array too. The element attached to the DOM is the same element in your array. Check my answer below.
1

The object in the DOM is the same. If you want to reuse the same tag again you should call

$(div#i).detach();

From jquery docs:

The .detach() method is the same as .remove(), except that .detach() keeps all jQuery data associated with the removed elements. This method is useful when removed elements are to be reinserted into the DOM at a later time.

If you use .remove() you will lose events and data associated with the element beeing removed. But even using remove() you can reuse the same element after by calling .appendTo() again.

Example on fiddler: http://jsfiddle.net/sKRCF/1 (sorry about the alerts, it's the easy way).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.