clone() vs clone(true)
HTML:
<b>Hello</b>
<p>, how are you?</p>
jQuery:
$('b').click(function () {
alert('Handler for .click() called.');
});
$('b').clone().prependTo('p');
Firstly, we are adding a .click() handler to all the b tags present in the DOM.
Then, we are creating a deep copy of the b element by using the DOM manipulation method called .clone() . Deep copy means that it copies the matched elements as well as all of their descendant elements and text nodes.
Next, we are adding this new cloned content inside of and before the existing p element by using the DOM insertion method called .prependTo() .
Trick
The simple trick here to resolve this issue is to pass a boolean value true to the .clone() method.
$('b').clone(true).prependTo('p');
This boolean value indicates whether event handlers should be copied along with the elements. The default value is to the false . So, when we were calling the .clone() method without passing any boolean value, it was just copying the elements but not the event handlers attached to it. But, when we pass the value true , it copies both the elements and any event handler attached to i
