0

var $parent = $('.parent'),
    $child = $('.child');

console.log($child);

$child.click(function(){
  console.log('clicked');
  $parent.replaceWith('<span class="child">abcd</span>');
});
.child{
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
  <span class="child">abcd</span>
</div>

I'm new to job as a Junior Web Dev, I am studying jQuery and finding it interesting. I came across this little code. So when I click on the "Child", why isn't the console generating the message "Clicked" multiple times when I click it. It showed 1 time and stopped.

Kiran Lala
  • 146
  • 9
  • 7
    It's because you are replacing the current element with a new DOM element. And the click event was bound with the original element only, not the new one generated in its place. – Mohit Bhardwaj Nov 20 '17 at 15:41
  • 2
    To fix this use delegated event handlers: https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements – Rory McCrossan Nov 20 '17 at 15:46
  • fyi it is also possible to bind the event to the parent element like `$parent.on('click', '.child', function(){console.log('clicked');});` so it would trigger multiple times, even if the child element is replaced – electrophanteau Nov 20 '17 at 15:46
  • Thanks guys. I studied Delegated Event Handlers as mentioned by Rory. Thanks @Mohit and Electrophanteau for the insights. – Kiran Lala Nov 22 '17 at 07:55
  • My code : $parent.on('click', '.child', function(){ console.log('clicked'); $child.replaceWith('1234'); }); – Kiran Lala Nov 22 '17 at 07:55

0 Answers0