0

So I'm rendering dynamic items using replaceWith() to replace elements inside a <div> tag. However, whenever I use replaceWith(), the element listeners in the initial load is wiped clean and need to be declared again. It's an okay way to ensure that the listeners still work but what if there were multiple listeners, manually copy pasting them is tedious. Is there a way to import or export jQuery event listeners?

Any insight would be much appreciated, thank you for reading.

diggledoot
  • 691
  • 8
  • 22
  • There's no way to query the DOM for the event handlers. In jQuery < v1.7 you could get the handlers that were hooked up via jQuery, but [this answer](https://stackoverflow.com/a/2388129/157247) says that doesn't work in v1.7 onward. Your best bet is probably to keep track of them in your code. (You *could* monkey-patch `on`, but that's a bit...dodgy.) – T.J. Crowder Jul 29 '20 at 11:16
  • 1
    That's a shame but I found a work around here, https://stackoverflow.com/questions/49162774/jquery-replacewith-function-and-event-handlers-in-memory. – diggledoot Jul 29 '20 at 11:28
  • Great! And of course, if you're swapping out an element for another element of the same type (as they were there, `button` for `button`), just don't swap it out; update its properties instead. – T.J. Crowder Jul 29 '20 at 11:32

0 Answers0