Introduction
W3C has introduced a new "template" tag that provides a mechanism to define HTML markup fragments as prototypes. In practice, a template can be used to insert fragments of HTML code into your page, for example
- <template id="rowTemplate">
- <tr>
- <td class="record"></td>
- <td></td>
- <td></td>
- </tr>
- </template>
Features
- The template code can be defined nearly anywhere; the head, body or even a frameset.
- Templates will not be displayed
- Templates are not considered to be part of the document, in other words using document.getElementById(“mytablerow”) will not return child nodes.
- Templates are inactive until used, in other words, enclosed images will not download, media will not play, scripts will not run, and so on.
Using templates
- <table id="testTable">
- <thead>
- <tr>
- <td>
- ID
- </td>
- <td>
- name
- </td>
- <td>
- </td>
- </tr>
- </thead>
- <tbody>
- <!-- rows to be appended here -->
- </tbody>
- </table>
- <!-- row template -->
- <template id="rowTemplate">
- <tr>
- <td class="record"></td>
- <td></td>
- <td></td>
- </tr>
- </template>
Use the following to clone the new row and append it to the table in JavaScript:
Q: Can we use templates?
- // get tbody and row template
- var t = document.querySelector("#testTable tbody"),
- row = document.getElementById("rowTemplate");
- // modify row data
- var td = row.getElementsByTagName("td");
- td[0].textContent = "1";
- td[1].textContent = "Sunny";
- td[2].textContent = "@sunny_delhi";
- // clone row and insert into table
- t.appendChild(row.content.cloneNode(true));

Join the conversation! Your thoughts help the community grow.