Many items in a web page are dynamically created with JavaScript.
This means that we’ve to listen to events that are emitted by them so that we can use them to do something other than display content statically.
In this article, we’ll look at how to listen to events on elements that are created dynamically with JavaScript.
Event Delegation
We can listen to events emitted on the container element that has the dynamically created elements.
In the event listener, we can check which item is emitting an event do the stuff we want depending on the element emitting the event.
This is possible because events emitted by an element bubble up to its parent and ancestor elements all the way to the body
and html
elements unless we stop it manually.
Therefore, the body
element’s event listener will pick up events from all its descendant elements if we allow them to propagate.
For instance, we can write the following HTML:
<div>
</div>
And create then write the following JavaScript to listen to click events emitted by the dynamically created p
elements:
const div = document.querySelector('div')
for (let i = 1; i <= 100; i++) {
const p = document.createElement('p')
p.className = i % 2 === 1 ? 'odd' : 'even'
p.textContent = 'hello'
div.appendChild(p)
}
document.addEventListener('click', (e) => {
if (e.target.className.includes('odd')) {
console.log('odd element clicked', e.target.textContent)
} else if (e.target.className.includes('even')) {
console.log('even element clicked', e.target.textContent)
}
});
In the code above, we get the div element with document.querySelector
.
Then we use a for loop to add p
elements inside the div 100 times.
We set the className
of the element to set the value of the class
attribute.
textContent
has the value of the content of the p
element.
Then we call appendChild
on the div to add the p
element inside the div.
Then to listen to click events on the p
elements we just added, we listen to the click of document
, which is the body
element.
We call addEventListener
to add the click listener to the body
element.
Then we pass in a callback as the 2nd argument of addEventListener
.
The e
parameter is the event object.
It has information about the original element that emitted the event.
We get the element that originally emitted the event with the e.target
property.
So we can get the value of the class
attribute of the element with the e.target.className
property.
And we get the value of the textContent
property with the e.target.textContent
property.
Conclusion
We can listen to events emitted by dynamically created HTML elements with event delegation.
We just listen to events from the ancestor of the elements that emit the events and then check which element emitted the event in the callback.