Because when you replace the original element, events bound to it are removed. You’ll need to re-attach the click
event handler on original
after the call to replacement.replaceWith(original)
:
$(function()
{
function replace()
{
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);
original.click(replace);
});
}
$('.x').click(replace);
});