Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create multiple buttons using array.protoype.forEach (javascript)

I am writing some code that will create multiple buttons based on the array given to the function. What I have done is that I used the array.prototype.forEach to test the function out by printing the contents of the array on the console. When that worked I tried to make some buttons but the buttons are not showing up on the page. I have tried adding document.body.appendChild(element); but all that did was give me errors. Is there a way to create multiple buttons based on an array of items using array.protoype.forEach?

This is my code:

var array = ["bill", "harry", "john", "timothy"];

array.forEach(element => 
  document.createElement(element)
//I tried adding document.body.appendChild(element); here but kept giving me errors

);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The first parameter you pass to document.createElement is a string that specifies the type of element to be created. Another problem in your code is that while the body of your function is multiline, you are not using {}, You can achieve your goal like this:

let array = ["bill", "harry", "john", "timothy"];

array.forEach(element=> { 
  let btn = document.createElement('button');
  btn.innerHTML = element;
  document.body.appendChild(btn);
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading