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

Making HTML buttons from an array of names, and inserting them into the DOM

I can’t figure out how to make these into buttons using the array:

var widgetButtons = ["Zoom In", "Zoom Out", "Pan", "Search"]

Any help would be appreciated. This is my code I am attempting to use

   <body>
   <div id="demo"></div>
   <script>
        var widgetButtons = ["Zoom In", "Zoom Out", "Pan", 
        "Search"];
   </script>
   </body>
   </html>

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 :

Here is another way to do it, using forEach().

IDs cannot contain spaces, so we remove the space from the item’s name/text before setting the id.

const widgetButtons = ["Zoom In", "Zoom Out", "Pan", "Search"]
const demo = document.getElementById('demo');

widgetButtons.forEach( (item, idx) => {
  const btn = document.createElement('button');
  btn.id = item.replace(' ', '');
  btn.innerText = item;
  demo.appendChild(btn);
});
<html>
  <body>
    <div id="demo"></div>
  </body>
</html>
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