Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Hiển thị phần tử mảng lên div khi click button bằng vanilla JavaScript


Để nhúng các phần tử mảng vào div, duyệt mảng và append vào div.

Ví dụ

const myArray = ["stone","paper","scissors"]; const embedElements = () => { myArray.forEach(element => { document.getElementById('result').innerHTML += `
${element}
<br />`; }); };

Giả định div có id result.

Code hoàn chỉnh

<!DOCTYPE html> <html lang="vi"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Display array</title> </head> <body> <div id="result"></div> <button onclick="embedElements()">Hiển thị dữ liệu</button> <script> const myArray = ["stone","paper","scissors"]; function embedElements(){ myArray.forEach(el => { document.getElementById('result').innerHTML += `
${el}
<br />`; }); } </script> </body> </html>

Kết quả

Khi nhấn nút Hiển thị dữ liệu, div hiển thị:

stone
paper
scissors

Dùng innerHTML += append. Với dữ liệu lớn, nên build string rồi gán một lần, hoặc dùng document.createElement appendChild để tránh reflow liên tục và XSS risk.