I have this code
<div id="container">
<table>
<tr>
<td>name1</td>
<td>age</td>
</tr>
<tr>
<td>Alex</td>
<td>12</td>
</tr>
</table>
</div>
I want to make many <tr>
tags and its contents but I want to change the value inside the <td>
how can I do that ? I have heard about cloneNode, but I did not find any resources about how to do this
CodePudding user response:
Instead of use simple table i suggest you to use tbody
and thead
(tbody
empty and thead
with row) like my example, then use forEach
for the data and fill tbody
like:
const data = [
['test', 10],
['test2', 11],
['test3', 12],
];
const table = document.querySelector('table');
data.forEach(el =>{
table.tBodies[0].innerHTML = `<tr><td>${el[0]}</td><td>${el[1]}</td></tr>`;
});
<div id="container">
<!-- empty template -->
<table border="1">
<thead>
<tr>
<td>name1</td>
<td>age</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
Sidenote:
I don't know your data structure, this is only an example.
Reference:
CodePudding user response:
You can use <template>
for holding a HTML content which is not rendered immediately but can be instantiated subsequently during runtime.
The <template>
element has a content
property (DocumentFragment), which contains the template DOM subtree. You can clone the template content and then modify the subtree.
const template = document.getElementById('data-template');
const node = template.content.cloneNode(true);
const td = node.firstElementChild.children;
td[0].textContent = "Jonh";
td[1].textContent = "14";
document.querySelector("table").appendChild(node);
<table>
<tr>
<td>name1</td>
<td>age</td>
</tr>
</table>
<template id="data-template">
<tr>
<td>Alex</td>
<td>12</td>
</tr>
</template>
CodePudding user response:
Use knockout js. It's very simple. You can even have fields in table and track changes etc.