Page Loading...
Run
Break Lines
Result
<!DOCTYPE html> <html> <head> <style> th, td{ padding: 10px; } </style> </head> <body> <h2>Create an HTML table dynamically:</h2> <div id="tableDiv"></div> <script> const tableDiv = document.getElementById('tableDiv'); const table = document.createElement('table'); const tbody = document.createElement('tbody'); const thead = document.createElement('thead'); // Set table border and width table.border = "1"; table.style.width = "100%"; table.style.borderCollapse = "collapse"; // Table header array const headerArr = ['Id', 'Name', 'Age']; // Create table header for(let i=0;i<headerArr.length;i++){ let th = document.createElement('th'); th.innerText = headerArr[i]; thead.appendChild(th); } // Table Data const data = [ {id: 1, name: 'John Doe', age: 24}, {id: 2, name: 'James Bond', age: 23}, {id: 3, name: 'Will Smith', age: 25}, ]; // Create Table Rows and Columns for(let i=0;i<data.length;i++){ let tr = document.createElement('tr'); for(let key of Object.keys(data[i])){ let td = document.createElement('td'); td.innerText = data[i][key]; tr.appendChild(td); } // Append table row to table body tbody.appendChild(tr); } table.appendChild(thead); table.appendChild(tbody); // Append table to table div(table container) tableDiv.appendChild(table); </script> </body> </html>