In this article, you will learn to make a list of buttons and add button to them with the help of Array, Event and DOM. Below is the example. To view the console's print line, you will need to click "Open on Replit"
To understand the code above, you need to read up about the following
Firstly,
var divButtons = document.getElementById("ButtonContainer");
You can access any HTML elements using the DOM by getElementById
Next, to add new elements, you can use the innerHTML to inject HTML codes.
divButtons.innerHTML += "<div><button id='Button" + i + "'> Button" + i + "</button></div>";
Notice the Button has a element id set to Button + i
To store the buttons for easy access later, we can use an array.
var aButtons = [];
Then we can use a for loop to find all of them and insert into the array using the ID number as the key.
for (var k = 0; k < 25; k++)
{
aButtons[k] = document.getElementById("Button" + k);
}
Finally, when we add event listener to each button, we can use the target's ID to identify which button was clicked.
aButtons[k].onclick = (event) =>
{
this.divDisplay.innerHTML = event.target.id + " Pressed";
}
Below is the output.
Comments