One way to achieve this is by adding a delegate event on the parent ul
element and checking if the clicked element is an LI
. If it is, you can toggle the class using classList.toggleClass
.
Additionally, considering user behavior, it's advisable to handle double clicks as well. For instance, when a user adds a to-do item, they may want to select and copy it.
const ul = document.querySelector("ul.item-list");
ul.addEventListener('click', function(event) {
if (event.target.tagName === 'LI')
event.target.classList.toggle('done')
})
.done {
text-decoration: line-through;
}
<ul class='item-list'>
<li class="bold red" random="23">Notebook <button>Delete</button></li>
<li>Jello <button>Delete</button></li>
<li>Spinach <button>Delete</button></li>
<li>Rice <button>Delete</button></li>
<li>Birthday Cake <button>Delete</button></li>
<li>Candles <button>Delete</button></li>
</ul>