Title: How to loop through buttons and avoid repetition in JavaScript?
Tags: javascript;html
Question: 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;
Comment: 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.

Here is the accepted answer: The element can't be assigned to anything. I think you need to add event listener for click.
Try this approach.
['b1', 'b2', 'b3', 'b4', 'b5'].forEach(id =&gt; {
document.getElementById(id).addEventListener('click', click);
ES5.1
['b1', 'b2', 'b3', 'b4', 'b5'].forEach(function(id) {
document.getElementById(id).addEventListener('click', click);
var ids = ['b1', 'b2', 'b3', 'b4', 'b5'];
for(var i = 0; i < ids.length; i++) {
document.getElementById(ids[i]).addEventListener('click', click);
Comment for this answer: When try the ES5 I get an error saying Invalid left hand for assignment in this line
document.getElementById(ids[i]) = click;
Comment for this answer: @Adam forEach is in ES 5.1
Comment for this answer: @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.
Comment for this answer: 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
Comment for this answer: 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.

Here is another answer: 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);

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 2, 'CommentCount': 1, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2017:00:12/11/17', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<javascript><html>', 'Title': 'How to loop through buttons and avoid repetition in JavaScript?', 'ViewCount': 624, 'id': 47757965, 'user_AboutMe': None, 'user_AccountId': None, 'user_DisplayName': None, 'user_Reputation': None, 'user_Views': None, 'user_id': None}}