0

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.getElementById("b3") = click;
document.getElementById("b4") = click;
document.getElementById("b5") = click;
1
  • Depending on what do you want to do with them. Yo can specify some class and use document.querySelectorAll("button.myButtonClass") to get HTMLCollection. Add some context to your question please. Commented Dec 11, 2017 at 17:26

2 Answers 2

4

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); 
}
Sign up to request clarification or add additional context in comments.

5 Comments

can also just iterate from 1 to 5 and prepend the b to avoid needing an array. forEach is still ES5 so the for loop is not required there if you are still keeping the array
When try the ES5 I get an error saying Invalid left hand for assignment in this line document.getElementById(ids[i]) = click;
@Adam forEach is in ES 5.1
In future, this code might become bit messy, as you might or might not need to add 10 or 100 more elements like this. In that case, you will have to keep adding elements to the array like 'b5', 'b6',...., 'b100'];. A better approach would be to use a class or attribute starts with here with document.querySelectorAll and the loop over it.. Just a suggestion.
@palaѕн you are right. This case only for fewer items. Maybe will be more items with same function, maybe functions will be changed for each button individually.
0

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); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.