Within document.ready, I store a selector in a variable (which I assume once evaluated, stores the element object in said variable), as I need to manipulate it many times.
ie. myVar = $('#mySpan');
What I’m storing is a span element within a div. One of the manipulations requires me to overwrite the contents of the div using the .html() function.
After, I need to reinsert that span element inside the div mentioned above and do so using the html() function.
The problem I have is that once the span element has been re-added, the variable myVar is no longer associated with the span element. I assume this is because it was deleted from the DOM and then re-added.
I know that jquery has the .detach() function, but that seems to only preserve attached events and data elements, but not actual references. I don’t even thing the .live() function would help in this case either.
EDIT:
If you want to preserve the content in a variable for later insertion, just simply store it in a variable using
.contents(), then reinsert it when needed.jQuery’s
.contents()method selects all content, including text nodes.Try it out: http://jsfiddle.net/bD2Ej/2/ (click the text to toggle)
This example toggles between the original and new content.
Original ansewr:
If you used
.detach()you would still need to store it in a variable.Here’s an example: http://jsfiddle.net/bD2Ej/
But are you sure you need
.html()? Could you just use.append()so the#mySpanisn’t overwritten in the first place?