183
rated 0 times
[
185]
[
2]
/ answers: 1 / hits: 5960
/ 3 Years ago, mon, august 23, 2021, 12:00:00
I am trying to apply event delegation and so I want to update the text when I click within the li element but when I click inside a element, it won't fire. I don't want to attach the event listener directly to li as the list can be updated and there can be any element type within li.
const menu = document.querySelector('.menu');
const textField = document.querySelector('p');
menu.addEventListener('click', e => {
if (e.target.matches('li')) {
textField.textContent = e.target.textContent;
}
});
li {
padding: 1em;
border: 1px solid red;
}
a {
border: 1px solid blue;
}
<div class=menu>
<ul>
<li><a>Home</a></li>
<li><a>Gallery</a></li>
<li><a>About us</a></li>
</ul>
<p></p>
</div>
More From » dom-events