Events not working while cloning by using .clone(true)

jquery

Solution

If you invert `.replaceWith()` with `.clone()` it'll work:

$('button').on('click', function(){
  $(this).clone(true).appendTo('body');
  $(this).replaceWith('<p>'+ $(this).text() +'</p>');
});

The `.replaceWith()` will clear all the events bound to the element (as discussed here). When you call `.clone()` after that, there's no events to retain.

My guess is that `.clone()` retains the base html even before the call to it (like in a internal variable) and `.clone(true)` retrieves that value and then bind the events.

Problem

I was just tried to answer this question. Actually the op has asked that the event not getting fired on a cloned element. while looking at his code, he had used .clone() function to accomplish his task, so what i suggested was to use `.clone(true)`. The doc says that if we pass the first argument as true in .clone() function, then the cloned copy would retain the data and their event handlers. But it is not behaving like so. Am i misunderstanding anything.. can any body guide me in the right direction..? DEMO Code taken from the fiddle, ``` $('button').on('click', function(){ $(this).replaceWith('<p>'+ $(this).text() +'</p>'); $(this).clone(true).appendTo('body'); }); ```

Original source

Related problems