MEHMET BALIOGLU

Easily add event listener to multiple DOM elements

Javascript Event Listener

Adding event listener to multiple DOM elements is one of the most pivotal techniques in order to achieve amazing effects with Javascript.

For example, let’s assume that we have multiple elements with a .inner class and clicking on them activates a function.

x= document.querySelectorAll(".inner");

x.forEach(item => {
  item.addEventListener("click", event => {
    item.classList.toggle("bluediv")
  })
})

In the above example, we place event listener upon all elements with the .inner class. It toggles the .bluediv class. Therefore, whenever we click on an element with this class, item.classList.toggle() adds or removes .bluediv class from this element.