I'm trying to build 2 html tables from 2 different JavaScript data arrays.
The first table is built fine and the structure looks great, but the second table is not populated with data.
I tried adjusting the naming, but I think because it's looking for "tbody" both times.
Is there another variable to adjust this, or maybe a better way to get 2 separate tables from 2 different data arrays?
I swapped the naming and added ID tags to tbody with no change. I was originally going to rename the data table, but it seems that the construction of the second table that grabs the tbody just resizes the first tbody.
<div style="float: left;margin-right:10px"> <table> <thead> <tr align="center"> <th><h3>Name</h3></th> <th><h3>Time</h3></th> <th><h3>Temp</h3></th> <th><h3>Peel</h3></th> </tr> </thead> <tbody id="tbody"></tbody> </table> </div> <script> const data = [ {name: "Apple", time: "25sec", temp: "100F", peel: "Peeler"}, {name: "Orange", time: "50sec", temp: "200F", peel: "Knife"}, ] const table = document.querySelector('tbody') data.forEach((item) => { table.insertAdjacentHTML( 'beforeend', `<tr> <td>${item.name}</td> <td>${item.time}</td> <td>${item.temp} </td> <td>${item.peel}</td> </tr>`) }) </script> <div style="float: left"> <table> <thead> <tr align="center"> <th><h3>Name</h3></th> <th><h3>Time</h3></th> <th><h3>Temp</h3></th> <th><h3>Peel</h3></th> </tr> </thead> <tbody></tbody> </table> </div> <script> <script> const data = [ {name: "Apple", time: "25sec", temp: "100F", peel: "Peeler"}, {name: "Orange", time: "50sec", temp: "200F", peel: "Knife"}, ] const table = document.querySelector('tbody') data.forEach((item) => { table.insertAdjacentHTML( 'beforeend', `<tr> <td>${item.name}</td> <td>${item.time}</td> <td>${item.temp}</td> <td>${item.peel}</td> </tr>`) }) </script>
There are some problems with your code. You declare
data
andtable
as constants in the first<script>
tag and then try to use the second<script>
tags to re-evaluate their values. (Constant variables cannot be reassigned). Additionally,document.querySelector('tbody')
will always select the first<tbody>
element found on the page. This will result in the same table being selected twice.This is how I refactored this code, but there are countless ways to solve this problem.
Consider extracting the row creation into a function and giving both tbody elements a unique ID to distinguish them.