How to Create a Table in JavaScript
In this article
To create a table in JavaScript, you build the elements and insert them into the page. The shortest working method is to create a <table>, <tbody>, <tr>, <td> and <th> elements with document.createElement(), append them to each other, and then append the finished table to a container already in your HTML. You do not need a library, and you do not need to write HTML strings unless you want to.
This guide uses plain DOM methods because they are safe, predictable and available in every browser. The same approach works whether you are building a small settings table for a smart home dashboard or a list of devices on a network. Labels and menu paths in browser developer tools can differ slightly by version and operating system, but the JavaScript methods below are standard.
What You'll Need
- A text editor (VS Code, Notepad++, or any plain editor).
- A modern browser such as Chrome, Firefox, Edge or Safari.
- An HTML file with a container element, for example
<div id="table-container"></div>. - Basic familiarity with opening the browser developer console (F12 or right-click > Inspect > Console).
Step-by-Step
Set up the HTML container. In your HTML file, add an empty element with an ID where the table will go. For example:
<div id="table-container"></div>. This gives JavaScript a fixed place to insert the table. If you skip this, you will need to append todocument.body, which works but makes layout harder to control.Create the table element. In your script, write
const table = document.createElement('table');. Optionally add a class for styling:table.className = 'device-table';. The table element is the outer wrapper; it will hold atheadand atbody.Create the header row. Create a
theadand atr:const thead = document.createElement('thead');andconst headerRow = document.createElement('tr');. Append the row to the head:thead.appendChild(headerRow);. Then append the head to the table:table.appendChild(thead);.Add header cells. For each column title, create a
thelement, set its text withtextContent, and append it to the header row. For example:const th = document.createElement('th'); th.textContent = 'Device'; headerRow.appendChild(th);. Repeat for each column. UsingtextContentinstead ofinnerHTMLprevents injected HTML from breaking your layout.Create the table body. Create a
tbodyelement:const tbody = document.createElement('tbody');and append it to the table:table.appendChild(tbody);. All data rows will go inside this body.Add data rows with a loop. If you have an array of objects, loop over it. For each item, create a
tr, then for each field create atd, settextContent, and append the cell to the row. Finally append the row totbody. Example:data.forEach(item => { const row = document.createElement('tr'); const cell = document.createElement('td'); cell.textContent = item.name; row.appendChild(cell); tbody.appendChild(row); });. Repeat the cell creation for each column.Insert the table into the page. Select your container:
const container = document.getElementById('table-container');and append the table:container.appendChild(table);. The table now appears in the browser. If nothing shows, check the console for errors and confirm the container ID matches.Style it if needed. Add CSS rules for
table,thandtdto set borders, padding and alignment. For example:table { border-collapse: collapse; } th, td { border: 1px solid #ccc; padding: 4px 8px; }. Styling is optional but makes the table readable.
Common Mistakes
- Appending cells to the table instead of a row. Cells must go inside a
tr, and rows must go insidetheadortbody. Appending atddirectly totableproduces invalid markup and unpredictable rendering. - Using
innerHTMLwith unescaped data. If the data comes from a user or an external source, settinginnerHTMLcan inject scripts or break the table. UsetextContentfor plain text. - Forgetting to append the table to the DOM. Creating elements in memory does nothing until you append the table to a container that is already in the document.
- Reusing the same element variable inside a loop without recreating it. Each cell and row must be a new element. Declaring
const cellinside the loop ensures that. - Assuming
getElementByIdruns before the DOM is ready. If your script is in the<head>withoutdefer, the container may not exist yet. Place the script at the end of<body>or useDOMContentLoaded.
Tips
- Build the table in a
DocumentFragmentfirst, then append it once. This reduces reflows and keeps the page responsive when adding many rows. - Use
table.createTHead()andtable.createTBody()for shorter, standard code. These methods are part of the DOM and work in all modern browsers. - Add a
captionelement for accessibility:const caption = document.createElement('caption'); caption.textContent = 'Devices on the network'; table.appendChild(caption);. - Set
scope="col"on header cells to help screen readers associate headers with data. - Keep data separate from rendering. Store rows in an array and write a single function that renders the table from that array; updating the array and re-rendering is easier than editing individual cells.
Troubleshooting
If the table does not appear, open the browser console and look for a red error. A TypeError: Cannot read properties of null usually means getElementById returned null because the ID is misspelled or the script ran before the element existed. Check the spelling and move the script to the end of the body.
If the table appears but looks like plain text, the elements may be nested incorrectly. Inspect the table in the Elements panel and confirm the structure is table > thead > tr > th and table > tbody > tr > td. If you see td directly under table, fix the append order.
If only the first row shows, check that you are creating a new tr inside the loop. Reusing one row variable and appending it repeatedly moves the same element rather than adding new ones.
If the table is present but empty, confirm that textContent is set before the cell is appended, and that the data array actually contains items. Log the array length to the console to verify.
If styling does not apply, check that your CSS selector matches the class or element you used, and that the stylesheet is loaded. Browser developer tools show which rules are active.
Frequently Asked Questions
Can I create a table without any HTML on the page?
Yes. Create the table and append it to document.body. However, a dedicated container gives you more control over placement and styling.
Do I need a library like jQuery to build tables?
No. The standard DOM methods shown here work in every modern browser and avoid extra dependencies.
How do I add a row after the table is already on the page?
Select the existing tbody and append a new tr with its cells, following the same pattern. The browser updates the display immediately.
What is the difference between createElement and innerHTML for tables?
createElement builds elements safely and lets you attach event listeners directly. innerHTML parses a string and is faster to write but risks injection if the data is not escaped.
Why does my table show an extra empty row?
You may have created a tr outside the loop and appended it once, then appended cells to it repeatedly. Check that row creation happens inside the loop.
Can I make the table sortable or filterable?
Yes, but that requires additional JavaScript. Keep the data in an array, sort or filter the array, then clear the tbody and re-render the rows. This is simpler and less error-prone than manipulating individual cells.