Universal event delegation in JavaScript

The code in the previous lesson is working, however, not without flaws. Let's analyze these disadvantages and find a more universal solution.

The disadvantage of our code will manifest itself when there are some nested tags inside li. In our case, let these be the i tags:

<ul> <li>item <i>italic</i> item</li> <li>item <i>italic</i> item</li> <li>item <i>italic</i> item</li> <li>item <i>italic</i> item</li> <li>item <i>italic</i> item</li> </ul>

In this case, clicking on the i tag will add an exclamation mark to the end of the tag i , and not the li tag, as we would like - after all, exactly the tag in which the event occurred gets into event.target.

You can solve the problem using the method closest:

list.addEventListener('click', function(event) { let li = event.target.closest('li'); if (li) { li.textContent = li.textContent + '!'; } });

Repeat the above solution.

enru