Advertisements
I am trying to build out 2 html tables from 2 different JavaScript data arrays.
The first table builds out fine and structure looks great but the second table doesn’t populate data.
I tried adjusting the naming but I think since it’s looking for "tbody" both times.
Is there another variable to adjust this or perhaps a better way to have 2 separate tables from 2 different data arrays?
I swapped the naming and added ID tags to the tbody with no change in results. I was going to just rename the data tables but seems like the construction of the second table grabbing tbody is just adjusting 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>
>Solution :
Consider extracting the row creation into a function and giving the two tbody elements unique ids to distinguish them.
function addRows(tbody, data) {
data.forEach((item) => {
tbody.insertAdjacentHTML('beforeend', `<tr>
<td>${item.name}</td>
<td>${item.time}</td>
<td>${item.temp} </td>
<td>${item.peel}</td>
</tr>`)
});
}
const data1=[{name:"Apple",time:"25sec",temp:"100F",peel:"Peeler"},{name:"Orange",time:"50sec",temp:"200F",peel:"Knife"},];
const tbody1 = document.querySelector('#tbody1');
addRows(tbody1, data1);
const data2=[{name:"Apple",time:"25sec",temp:"100F",peel:"Peeler"},{name:"Orange",time:"50sec",temp:"200F",peel:"Knife"},];
const tbody2 = document.querySelector('#tbody2');
addRows(tbody2, data2);
<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="tbody1"></tbody>
</table>
</div>
<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 id="tbody2"></tbody>
</table>
</div>