Display Array Items on a Div Element 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 −
Example
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 −
Example
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div id="result"></div> <button onclick="embedElements()">Show Data</button> <script> { 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 }); }; } </script> </body> </html>
Output
On clicking the button “Show Data”, the following is visible −
Advertisements