Skip to content Skip to sidebar Skip to footer

How To Loop Through Buttons And Avoid Repetition In Javascript?

How can I use a loop to go through these buttons instead of writing this 5 times. document.getElementById('b1') = click; document.getElementById('b2') = click; document.getElemen

Solution 1:

The element can't be assigned to anything. I think you need to add event listener for click.

Try this approach.

ES6

['b1', 'b2', 'b3', 'b4', 'b5'].forEach(id => { 
     document.getElementById(id).addEventListener('click', click); 
});

ES5.1

['b1', 'b2', 'b3', 'b4', 'b5'].forEach(function(id) { 
     document.getElementById(id).addEventListener('click', click); 
});

ES5

var ids = ['b1', 'b2', 'b3', 'b4', 'b5'];

for(var i = 0; i < ids.length; i++) {
   document.getElementById(ids[i]).addEventListener('click', click); 
}

Solution 2:

In addition to Suren Srapyan, instead of using element id's you can also do with class name/element name Like below.

var x = document.querySelectorAll(".example");
for(i=0; i < x.length; i++ )
    x[i].addEventListener('click', click); 

Post a Comment for "How To Loop Through Buttons And Avoid Repetition In Javascript?"