How to add event listener to multiple elements in JavaScript
In this post we will give you information about How to add event listener to multiple elements in JavaScript. Hear we will give you detail about How to add event listener to multiple elements in JavaScriptAnd how to use it also give you demo for it if it is necessary.
we are going to learn about how to add an event listener to multiple html elementsusing JavaScript.
Normally, we add an event listener to the single element using the addEventListener() method.
// accessing the elementconst element = document.querySelector('.blue');// adding the event listenerelement.addEventListner('click', (e)=>{ console.log('someone hit me');});
Adding event listener to multiple elements
To add the event listener to the multiple elements, first we need to access the multiple elements with the same class name or id using document.querySelectorAll() method then we need to loop through each element using the forEach() method and add an event listener to it.
// accessing the elements with same classnameconst elements = document.querySelectorAll('.my-box');// adding the event listener by loopingelements.forEach(element => { element.addEventListner('click', (e)=>{ console.log('someone hit me'); });});
If your elements having different class-names rather than the same class name, you can add it like this.
const element1 = document.querySelector('.red');const element2 = document.querySelector('.blue');const element3 = document.querySelector('.green');[element1, element2, element3].forEach((element)=>{ element.addEventListner('click', (e)=>{ console.log('someone hit me'); });});
Hope this code and post will helped you for implement How to add event listener to multiple elements in JavaScript. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs