Last active
July 24, 2025 10:22
-
-
Save etigui/74980eed346a3dbed13f3c48ee4b1e8d to your computer and use it in GitHub Desktop.
Creating HTML table dynamically using javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!DOCTYPE html> | |
| <html lang="en"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <meta http-equiv="X-UA-Compatible" content="ie=edge"> | |
| <title>Table</title> | |
| </head> | |
| <body> | |
| <div id="myDivTable"></div> | |
| <script> | |
| // Data to add to the table. Like json db data | |
| var data = {results: [{id: 1, name: 's1'}, {id: 2, name: 's2'},{id: 3, name: 's3'}]}; | |
| createTable(data.results); | |
| // Create table | |
| function createTable(data) { | |
| // Check if at least one value exists in the json array | |
| if(data.length > 0 && Array.isArray(data)){ | |
| // Get div to create table | |
| var mytable = document.getElementById("myDivTable"); | |
| // Clear table if exists | |
| var t = document.getElementById("myTable"); | |
| if(t){ | |
| t.remove(); | |
| } | |
| // Create table | |
| var table = document.createElement('table'); | |
| table.setAttribute('id', 'myTable'); | |
| table.setAttribute("border", "1"); | |
| table.style.borderCollapse = "collapse"; | |
| table.appendChild(createTHead(data)); | |
| table.appendChild(createTBody(data)); | |
| mytable.appendChild(table); | |
| } | |
| } | |
| // Create table head | |
| function createTHead(data){ | |
| var keys = Object.keys(data[0]); | |
| var thead = document.createElement('thead'); | |
| var tr = document.createElement('tr'); | |
| for (var col = 0; col < keys.length; col++) { | |
| var th = document.createElement('th'); | |
| th.appendChild(document.createTextNode(keys[col])); | |
| tr.appendChild(th); | |
| } | |
| thead.appendChild(tr); | |
| return thead; | |
| } | |
| // Create table body | |
| function createTBody(data){ | |
| var keys = Object.keys(data[0]); | |
| var tbody = document.createElement('tbody'); | |
| for (var row = 0; row < data.length; row++) { | |
| var tr = document.createElement('tr'); | |
| for (var col = 0; col < keys.length; col++) { | |
| var td = document.createElement('td'); | |
| td.appendChild(document.createTextNode(data[row][keys[col]])); | |
| tr.appendChild(td); | |
| } | |
| tbody.appendChild(tr); | |
| } | |
| return tbody; | |
| } | |
| </script> | |
| </body> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I used some of your code. Thanks for sharing !