New to all this and could use a little help, please.
I have an array that looks something like this:
contactArray = [{"Name":"Blake Janacek","Title":"Marketing Manager"},{"Name":"Dominic Flanders","Title":"Project Manager"}];
I’m trying to display a table with headers repeating each array object like this:
<table id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th>Name</th>
<th>Title</th>
</tr>
</thead>
<tbody>
<div id="list"></div>
<template id="template">
<tr>
<td>{name}</td>
<td>{title}</td>
</tr>
</template>
</tbody>
</table>
The problem I’m having is the data from the array is displaying above the header and not formatted. Here’s what I’m trying:
const html = contactArray.map(obj => {
let item = document.querySelector('#template').innerHTML;
item = item.replace('{name}', obj.Name);
item = item.replace('{title}', obj.Title);
return item;
});
document.querySelector('#list').innerHTML = html.join('');
Thank you
Oh, and here’s a fiddle
https://jsfiddle.net/t69bz54o/
3
Answers
You should not have a
div
outside of atr
element inside atable
.You can achieve the same by assigning the
#list
id to thetbody
element instead, like this:The JS should work as-is. Although there could be some performance improvements such as preloading the template DOM before the loop, so search is not done multiple times
Html part
JavaScript Part
The above code works fine, but there is the need for some CSS tricks for alignment.
The above answers will probably work as expected. I would still like to point out that with the template literals in ES6 you can achieve the same effect in an easier way:
The template literal is supplied directly in the JavaScript code section.