I need clarity, Whether addEventListener be dynamically called on DOM element which gets updated.
domelemet1 is fired on event click, then in that event function call it gets updated to random DOM element, now whether the past DOM only gets fired or the updated DOM gets fired? I checked that past DOM gets fired, I just need Clarification.
2
Answers
When you do:
you’re adding an event listener to the DOM element that the
domElement1
variable refers to, not to the variable itself. There’s no ongoing connection between the variable and the event listener. You can assign a different value to the variable, or even let the element go out of scope and cease to exist:The variables you use to refer to DOM elements aren’t the actual elements, they’re just a means of interacting with the elements.
In a comment on the question you asked:
What matters is what element you attached the event handler to. If you attached it to Box1, then it’s attached to Box1. It doesn’t matter whether you change what classes Box1 has, and or what you do with Box2. It doesn’t matter how you got your reference to Box1. For instance, if you got it by doing
document.querySelector(".some-class")
, it doesn’t matter whether the element still has that class later. The class was only used to find the element at that moment in time.If the element with the class
.active-box
is dynamically moved to a different position in the DOM, the original click event listener attached to it will no longer work, because it is only associated with the original position of the element. Use event delegation: Attach the event listener to a parent element that is not moved, and then use theevent.target
property to determine if the clicked element matches the selector.active-box
.