Display array items on a div element on click of button using vanilla JavaScript

To embed the elements of an array inside a div, we just need to iterate over the array and keep appending the element to the div

This can be done like this −


const myArray = ["stone","paper","scissors"];
const embedElements = () => {
   myArray.forEach(element => {
      document.getElementById('result').innerHTML +=
      `<div>${element}</div><br />`;
      // here result is the id of the div present in the DOM

This code makes the assumption that the div in which we want to display the elements of array has an id ‘result’.

The complete code for this will be −


 Live Demo

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
   <div id="result"></div>
   <button onclick="embedElements()">Show Data</button>
   const myArray = ["stone","paper","scissors"];
   function embedElements(){
      myArray.forEach(el => {
         document.getElementById('result').innerHTML +=`<div>${el}</div><br />`;
         // here result is the id of the div present in the dom


On clicking the button “Show Data”, the following is visible −

Updated on: 18-Aug-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started