Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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