How to use addEventListener and getElementsByClassName to pass the element ID to the event listener with JavaScript?

Sometimes, we want to use addEventListener and getElementsByClassName to pass the element ID to the event listener with JavaScript.

In this article, we’ll look at how to use addEventListener and getElementsByClassName to pass the element ID to the event listener with JavaScript.

How to use addEventListener and getElementsByClassName to pass the element ID to the event listener with JavaScript?

To use addEventListener and getElementsByClassName to pass the element ID to the event listener with JavaScript, we can use event delegation.

For instance, we write:

<ul>
  <li class="menu" id="bob">Robert Smith</li>
  <li class="menu" id="jane">Jane Doe</li>
  <li class="menu" id="sue">Susan Carter</li>
</ul>

to add an ul with some li elements.

Then we write:

document.onclick = (e) => {
  if (e.target.className === 'menu') {
    console.log(e.target.id)
  }
}

to set document.onclick to a function that checks the className of the clicked element.

If the className is 'menu', then we get the ID of the element we clicked on with e.target.id.

Conclusion

To use addEventListener and getElementsByClassName to pass the element ID to the event listener with JavaScript, we can use event delegation.