Sometimes, we want to attach event to dynamic elements in JavaScript.
In this article, we’ll look at how to attach event to dynamic elements in JavaScript.
How to attach event to dynamic elements in JavaScript?
To attach event to dynamic elements in JavaScript, we can listen for events on document
.
For instance, we write
document.addEventListener("click", (e) => {
if (e.target && e.target.id === "brnPrepend") {
//...
}
});
to call document.addEventListener
to listen to click events on the whole document.
In the event listener callback, we check if the ID of the element that triggered the click is brnPrepend
.
If it is, then we do something.
We do the element’s ID check with e.target.id === "brnPrepend"
.
e.target
is the actual element that triggered the event.
Conclusion
To attach event to dynamic elements in JavaScript, we can listen for events on document
.