Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attaching a click event to multiple elements at once? [duplicate]

Here is my code in jQuery:

$('.paragraph, .section, .heading').on('input', function (e) {
   localStorage.setItem($(this).attr('id'), $(this).text());
});

Is there any JavaScript equivalent where I could attach all events at once?

like image 987
SanJeet Singh Avatar asked Dec 30 '15 04:12

SanJeet Singh


People also ask

How do you add an event listener to multiple elements with the same class?

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.

Why is this jquery Ajax click event firing multiple times?

This happens because somewhere in your code, you're rebinding the event handler without first unbinding it.


2 Answers

You could use querySelectorAll with your multiple element selectors, then add the event listeners to each one

var elements = document.querySelectorAll(".a, .b");
for (var i = 0; i < elements.length; i++) {
  elements[i].addEventListener("click", function() {
    console.log("clicked");
  });
}
like image 50
Andrew Brooke Avatar answered Sep 21 '22 05:09

Andrew Brooke


Suppose you want to add click event to multiple elements, then set their class name as for example demo

demos= document.getElementsByClassName('demo');
for (var i = 0; i < demos.length; i++) {
    demos[i].addEventListener('click',redirect,false);
}
function redirect(){
    alert(this.id);
}

WORKING FIDDLE

like image 32
Hemal Avatar answered Sep 19 '22 05:09

Hemal