0

I ran into something weird playing with events on Javascript, I tried adding events to an element, and modifying the parent element inner HTML deleted the events, here is an example :

const content = document.body
const p = document.createElement('p')
p.innerHTML = "I am just a text element."

p.addEventListener("click", function(event){
    console.log("The event works..")
})

content.appendChild(p)
content.innerHTML += "<div> </div>"

Now, clicking on the "p" element should trigger the event but the last line "content.innerHTML..." prevents it. It somehow delete the event.

I know modifying the inner HTML like this is not a good practice, but still, can someone explain why the events are deleted ?

Thank you !

vhoyet
  • 1
  • 2
  • 2
    The `p` you created and the `p` you manually wrote via `innerHTML` are not one and the same. – Mitya Jan 06 '20 at 13:39
  • indeed! add the listener to the `content` instead, and reach the `p` via `event.target.closest('p')` – Andrea Giammarchi Jan 06 '20 at 13:43
  • Hi guys, thanks you for your answers ! I know the two "p" are not the same, i'm trying to call the first "p" event. I could had only a letter or every other tag in the content inner HTML, I will fix my post to make more sense. Also, I'm not trying to fix a problem, I want to understand why modifying the inner HTML of the parent element delete the event.. – vhoyet Jan 06 '20 at 13:50
  • Looks like a duplicate of https://stackoverflow.com/questions/5113105/manipulating-innerhtml-removes-the-event-handler-of-a-child-element – mzmm56 Jan 06 '20 at 14:17
  • Indeed this is, thanks you I couldn't find it myself, should I delete my post then ? – vhoyet Jan 06 '20 at 14:22
  • It's not that it deletes the event - it's that *you* delete the element the event was bound to, by overwriting the contents of its container element. The `p` ceases to exist, so its event cannot be called. – Mitya Jan 06 '20 at 14:27
  • Yes I delete the element but I thought that by recreating it, it would recreate the events to. But I found here : https://stackoverflow.com/questions/5113105/manipulating-innerhtml-removes-the-event-handler-of-a-child-element that the attributes cannot be mapped into inner HTML.. Thank you ! – vhoyet Jan 06 '20 at 14:32
  • You haven't recreated the element; you've made a new element. That's the takeaway here. – Mitya Jan 06 '20 at 15:31

0 Answers0