ในการฝังองค์ประกอบของอาร์เรย์ภายใน div เราเพียงแค่ต้องวนซ้ำอาร์เรย์และผนวกองค์ประกอบเข้ากับ div ต่อไป
สามารถทำได้ดังนี้ −
ตัวอย่าง
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
});
}; รหัสนี้ทำให้สันนิษฐานว่า div ที่เราต้องการแสดงองค์ประกอบของอาร์เรย์มี id 'ผลลัพธ์'
รหัสที่สมบูรณ์สำหรับสิ่งนี้จะเป็น -
ตัวอย่าง
<!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> ผลลัพธ์

เมื่อคลิกปุ่ม “แสดงข้อมูล” จะเห็นสิ่งต่อไปนี้ -
