Template Element Clones Table Rows
A template element stores one row once; content.cloneNode(true) stamps out an independent row per record without building innerHTML strings.
Code
// 页面里有一张 <table id="files">,行结构放在 <template id="row"> 里:
// <template id="row"><tr><td class="name"></td><td class="size"></td></tr></template>
// 模板内容不属于渲染树:克隆时才生成节点,避免逐行拼 innerHTML 字符串
const template = document.querySelector('#row');
const files = [
{ name: 'report.pdf', size: '2.1 MB' },
{ name: 'notes.txt', size: '12 KB' },
];
const tbody = document.querySelector('#files tbody');
for (const file of files) {
// cloneNode(true):模板只解析一次,每条记录克隆出独立的行
const row = template.content.cloneNode(true);
row.querySelector('.name').textContent = file.name;
row.querySelector('.size').textContent = file.size;
tbody.append(row);
}
console.log('rows rendered:', tbody.children.length);
console.log('template still empty:', template.content.children.length);How it works
Repetition is confined to for (const file of files) — the rest of the file is straight-line.
Module-level bindings hold the data — template, files, tbody — with no function scope in between.
Watch out for
- A browser is the runtime here:
documentare not available in Node.
Using it
Running the file prints labeled results such as rows rendered:, template still empty: — each operation’s effect is visible in the output.
Key statements
const tbody = document.querySelector('#files tbody');
row.querySelector('.name').textContent = file.name;
row.querySelector('.size').textContent = file.size;
Interactive Tools for This Topic
FAQ
- Does Template Element Clones Table Rows run in plain Node.js?
- No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.