We can easily add an event listener to an element in JavaScript by using either getElementById or querySelector properties on the document object.

example:

Copy to Clipboard

But, here we are adding the event listener to only one element.

Suppose we have a list of elements which are draggable and when we drop them in any drop zone, we need to identify the element which was dropped. Here are we may want to attach the same event listener for dragstart event on all elements.

example:

Copy to Clipboard

 

Way 2:

If all the elements that you want to add event listener to are under a same element, we can add event listener to the parent element and capture the events which will be arrived onto this element through event bubbling. If you want to use this way, make sure that the events are not stopped from bubbling through stopPropagation or stopImmediatePropagation methods.

example:

HTML:

Copy to Clipboard

JS:

Copy to Clipboard

In this example, we also checked the id of the element on which the click happened to do something only when the user clicks on the child element.

Suppose if we have the following lines of code in JS

Copy to Clipboard

Now, if the user clicks on the blue div element, the event will not reach the parent element since we stopped event bubbling by using stopPropagation.