site icon

Hi, I’m Chris

I am a web developer teaching
regular people how to code

~ Welcome to my blog ~

Javascript: Add Event Listeners To A List Of Elements

When using Javascript, we can often need to add an event listener to a list of elements.

A common use is when we have a list and we want to trigger a function when any of the list items are clicked:

<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
  <li>Item 5</li>
</ul>
<!-- output the selected list text -->
<h3></h3>

We can then use a for...of loop to loop though all of our "li" elements and add an event listener:

// select all list items
const links = document.querySelectorAll("li");
// for-of loop
// gives us a constant value for each "link" in our list of links:
for (const link of links) {
  // we can then use this link and add an event listener:
  link.addEventListener("click", setSelected);
}

// function to run when list item is clicked
function setSelected(e) {
  document.querySelector('h3').innerText = `Selected  ${e.target.innerText}`
}

Now when we click on any link, we can access the full event information including the text content of each link.

Live demo on codepen


- By Chris Dixon

Chris Dixon is a web developer and teacher. Teaching thousands of students mainly in Vue.js React.js, WordPress and web development.