Categories
JavaScript Answers

How to attach event to dynamic elements in JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *