Search code examples
javascriptjqueryhtmlclone

How do I edit the contents of HTML5 template tag with jQuery before cloning?


I am currently trying to set up a template that I can fill out in a for loop and clone each time. This is what I have so far which works fine for cloning the templates HTML but I am stuck trying to manipulate my template before cloning it.

Trying to do something like a find() on a clone does not work, I think it has something to do with the template being a #document-fragment?

Could somebody give me an example with jQuery on how to do this? Maybe something as simple as manipulating the h1 title before cloning the template?

<div class="template-holder"></div>

<template class="my-custom-template">
  <div class="example">
    <h1>Example</h1>  
    <h2>Example 2</h2>
    <div class="customDiv">Testing</div>
  </div>
</template>

Javascript:

var template = $('.my-custom-template');

var clone = template.clone();

$('.template-holder').append(clone.html());

JSFiddle example:

https://jsfiddle.net/Lmyyyb4k/2/

Edit:

It looks like jQuery itself does not have any support for document fragments: http://james.padolsey.com/stuff/jQueryBookThing/#doc-fragments

So I guess I will have to combine some vanilla JS with jQuery.


Solution

  • If you use a different element than template, it works:

    <div class="template-holder"></div>
    
    <div class="my-custom-template" style="display:none">
      <div class="example">
        <h1>Example</h1>  
        <h2>Example 2</h2>
        <div class="customDiv">Testing</div>
      </div>
    </div>
    

    This would manipulate the h1 title in the template before cloning the template:

    var template = $('.my-custom-template');
    template.find("h1").text("Changed H1 Title!");
    
    var clone = template.clone();
    $('.template-holder').append(clone);
    clone.show();