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?
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.
This happens because somewhere in your code, you're rebinding the event handler without first unbinding it.
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");
});
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With