Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
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

 Answers
5

If you want the li and not the anchor or any other child element, use closest


const li = e.target.closest("li");
if (li) { /* do whatever */ }

[#971] Friday, August 13, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ellisw

Total Points: 625
Total Questions: 92
Total Answers: 88

Location: Kazakhstan
Member since Mon, Sep 26, 2022
2 Years ago
ellisw questions
Fri, Nov 20, 20, 00:00, 4 Years ago
Sat, Jun 20, 20, 00:00, 4 Years ago
Tue, Apr 21, 20, 00:00, 4 Years ago
;