Javascript Job Interview Question and Answer: Create multiple buttons with Javascript

How to make 20 buttons appear in the DOM by using javascript.

I applied for a web developer job opening recently and I was asked to create a group of buttons with the text “Button” and the index number of the button written inside the button without writing any html. I had to use javascript to render these buttons in the html and I needed to make 20 buttons. In my head the first thing I thought was that I will need to use a for loop that will count from 1 to 20. Then inside that loop I need to create a button element and attach it to the body of the html document. To write the text I will use innerHTML plus the index number to get the appropriate button text inside of the button. This did indeed create 20 buttons in the body of the html but I wasn’t satisfied. I wanted to make sure the button would tell me which button it was when I clicked on it. I added an EventListener to listen for a mouse 'click' on the button and then I used an alert to show the correct button was clicked.

let i = 1;
let body = document.getElementsByTagName("body")[0];

for (i; i <= 20; i++) {
  let button = document.createElement("button");
  button.innerHTML = 'Button '+i;
  body.appendChild(button);
  button.addEventListener ("click", function() {
    alert(this.innerHTML);
  });
}

Here is a full Plunker example below:

Initially, the script.js was not attaching the buttons to the body, nothing was showing. I realized by default plunker has the script.js tag in the head of the html document. I realized I needed to move the script.js tag down below the closing body tag. This is normally a best practice to have the script.js load at the bottom of the html document.

References: https://codepen.io/davidcochran/pen/WbWXoa
https://plnkr.co/edit/6NL2VQmSfEnZsz3bJ7iu?p=preview