Reputation: 3871
I'm up to complete jQuery/ajax - based UI, and I have a little problem: I need to save all nodes below <div id="mainpanel">
but to retain events attached with them, so I could to interact with this previous DOM.
Let's say this DOM:
<div id="mainpanel">
<a href="#" id='firstopt'>First option</a>
<a href="#" id='secopt'>Second option</a>
</div>
I have click handlers both with #firstopt and #secopt. If I click one of them, in next step I want to be able to go back and to have exactly the same DOM above. Part of that I'm able to achieve by simply saving current DOM I want to be able to go back to:
var currentDom=$('#mainpanel').html();
and restoring when I need it:
$("#mainpanel").html(currentDom);
now after step above, I have first DOM, but without every single event that was attached to nodes below. How to save them as well?
Upvotes: 1
Views: 701
Reputation: 4183
Use the .detach() function from jQuery and store the return value:
var elements = $(".someSelector").detach();
And then re-add them:
$(".container").append(elements);
This should keep all jquery related events attached to it.
Upvotes: 2
Reputation: 3965
May be I misunderstood. But I think when you try to use this DOM elements again, It will have a duplicate id. So you can not handle any event again. I think you should use class instead of ID.
<div id="mainpanel">
<a href="#" id='firstopt' class='yourClass'>First option</a>
<a href="#" id='secopt' class='yourClass'>Second option</a>
</div>
Now you can handle with class above!
Upvotes: 0
Reputation: 816384
Instead of serializing the DOM to HTML (a process in which you will loose event handler bindings), just keep a reference to the node(s):
var currentDom = $('#mainpanel').children();
$("#mainpanel").empty().append(currentDom);
Also have a look at .detach()
for removing the children from the container.
Depending on the overall context, instead of keeping a reference to DOM elements and their event handlers, event delegation might be a better solution.
Upvotes: 1