0

I'm using html() to replace content of the element:

<div class="page">
  <p>
  cheers
  </p>
</div>

Jquery:

$('body').on('click', '.page', function() {
var news=Math.floor((Math.random() * 10) + 1);
$(this).html(news);
 });

The click events are registered successfully but the when .html() is used the documentation says:

Additionally, jQuery removes other constructs such as data and event handlers from child elements before replacing those elements with the new content.

Why is the behavior not same when using click()?

I've also read on several forums to refrain from using onClick() as it doesn't comprise of modern methods. Is there a way to re-attach the event handlers such that the events register?

  • 2
    "*a way to re-attach the event handlers*" - the code you've provided is *already* using event delegation, so the code you've provided will work for new `.page` elements when they are added. If you had `$(".page").click(...` then it would only work for page elements that exist at the time, or if you included the relevant click handler on the elements that are actually being replaced (ie those within `.page`) then we could suggest you also use event delegation for those. – freedomn-m Aug 25 '22 at 09:45
  • 2
    `$("selector").click(...` will only work for elements that exist at the time the code runs. This is because `$("selector")` can only find elements that exist. If you delete those elements using `.html(newhtml)` then they don't exist so don't have click events. If you create new ones they don't have events because they didn't exist when you assign click handlers to elements. `onclick=` works because it's part of the html, but requires a global function. $("parent").on("click", "selector"...` works because the "parent" (`body` in your case) exists when the code runs. – freedomn-m Aug 25 '22 at 09:47
  • 1
    There's a lot more info here: https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements – freedomn-m Aug 25 '22 at 10:03

0 Answers0