Events not registering after replaceWith

Posted by strager on Stack Overflow See other posts from Stack Overflow or by strager
Published on 2009-04-20T22:07:12Z Indexed on 2010/05/14 23:34 UTC
Read the original article Hit count: 203

Filed under:
|
|

When I replaceWith an element to bring one out of the DOM, then replaceWith it back in, events registered to it do not fire. I need to events to remain intact.

Here's my Javascript:

var replacement = $(document.createElement('span'));
var original = $(this).replaceWith(replacement);

replacement
    .css('background-color', 'green')
    .text('replacement for ' + $(this).text())
    .click(function() {
        replacement.replaceWith(original);
    });

Live demo

In the demo, when you click an element, it is replaced with another element using replaceWith. When you click the new element, that is replaced with the original element using replaceWith. However, the click handler does not work any more (where I would think it should).

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about events