Categories
JavaScript Answers

How to add event binding on dynamically created elements with JavaScript?

Spread the love

Sometimes, we want to add event binding on dynamically created elements with JavaScript.

In this article, we’ll look at how to add event binding on dynamically created elements with JavaScript.

How to add event binding on dynamically created elements with JavaScript?

To add event binding on dynamically created elements with JavaScript, we can use event delegation.

For instance, we write

const hasClass = (elem, className) => {
  return elem.classList.contains(className);
};

document.addEventListener(
  "click",
  (e) => {
    if (hasClass(e.target, "foo")) {
      console.log("foo");
    } else if (hasClass(e.target, "bar")) {
      console.log("bar");
    } else if (hasClass(e.target, "baz")) {
      console.log("baz");
    }
  },
  false
);

to call document.addEventListener with 'click' to listen for all clicks events on the page.

In the click event handler, we get the element we clicked on with e.target.

Then we call hasClass to check if the class has the given className.

We use elem.classList.contains to check if the className is included in the class attribute of the element.

Conclusion

To add event binding on dynamically created elements with JavaScript, we can use event delegation.

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 *