tags:

views:

19

answers:

2

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.

+1  A: 

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.

var myVar;

// Add the new content, and append the element stored in myVar
$('#somediv').toggle(function() {
    myVar = $(this).contents();
    $(this).html('some new content<br>');
}, function() {
    $(this).html( myVar );
});
​

Original ansewr:

If you used .detach() you would still need to store it in a variable.

Here's an example: http://jsfiddle.net/bD2Ej/

   // Detach and reference the element in a variable
myVar = $('#mySpan').detach();

   // Add the new content, and append the element stored in myVar
$('#somediv').html('somecontent').append( myVar );

But are you sure you need .html()? Could you just use .append() so the #mySpan isn't overwritten in the first place?

patrick dw
What happens if the span element has to be reinserted between some plain text? That's why I used .html()
Chrys G.
@genbayer - I would need to see your specific situation. Is the plain text part of the new `.html()` content? Or was it existing, and also needs to be preserved?
patrick dw
Basically, this is what I need to doOriginal content:[div]original content text [span] and some more text[/div]Then, I need to overwrite the content in the div above:[div]new content[/div]Finally, I need to replace the content in the div with what was there originally. So, once again:[div]original content text [span] and some more text[/div]
Chrys G.
@genbayer - If you're saying that you need to replace it *at a later time*, then just store it all in a variable, and add it later. I'll update my answer in a minute.
patrick dw
+1  A: 

Try clone();

myVar = $('#mySpan').clone();
$('#mySpan').remove();
$('#somediv').html(myVar);

http://api.jquery.com/clone/

nicholasklick