HTML - Tags - <template>

#132 of 147
template

 <html>
 <body>
     <template id="comment-template">
         <li class="comment">
             <hr />
             <span class="comment-date">></span>
             <span class="comment-username">></span>
             <span class="comment-location">></span>
             <span class="comment-text">></span>
         </li>
     </template>
     <div>
         <p>Comments:</p>
         <ul id="generated-comments"></ul>
     </div>
     <script>
         var comments = [
             { "username": "william", "location": "NY", "date": "8/11/17", "text": "..." },
             { "username": "james", "location": "FL", "date": "8/11/17", "text": "..." },
             { "username": "alex", "location": "VT", "date": "8/11/17", "text": "..." },
             { "username": "sarah", "location": "CA", "date": "8/11/17", "text": "..." }
         ];
         var generated = document.querySelector('#generated-comments');
         var template = document.querySelector('#comment-template').content;
         for (var i = 0; i < comments.length; i++) {
             var comment = comments[i];
             var commentNode = template.cloneNode(true);
             commentNode.querySelector('.comment-username').innerText = comment.username;
             commentNode.querySelector('.comment-location').innerText = comment.location;
             commentNode.querySelector('.comment-date').innerText = comment.date;
             commentNode.querySelector('.comment-text').innerText = comment.text;
             generated.appendChild(commentNode);
         }
     </script>
 </body>
 </html>
 

The template element contains a fragment of HTML code that can be used as a prototype (a template) to generate additional elements dynamically using Javascript.

The template element is a hidden element. The browser will parse the element for validity, but it will not display it.

The template element helps keep presentation markup out of Javascript and in the document.

A live example:


Comments:


    See also: slot

    N of

    Ads by Google


    Ask a question, send a comment, or report a problem - click here to contact me.

    © Richard McGrath