23

I'm having some trouble with this:

template = $("#template");
$(template).attr("id", "newid");

$(template).appendTo("body");

What I want to do is assign an id to the template, then amend the content. Trouble is, I am currently referring to the actual template element, and so the id is changing that. On using this template again, I cannot select as the id is different.

Any advice on optimal approach?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Damien Roche
  • 13,189
  • 18
  • 68
  • 96
  • Not entirely sure what you what you mean? If you want to create an element from another, perhaps you want to use jQuery's `clone()` method? http://api.jquery.com/clone/. – Jack Franklin Jul 09 '11 at 18:22

6 Answers6

21

Clone the object:

template = $("#template").clone();
template.attr("id","newid");
template.appendTo("body");
Ujjwal Manandhar
  • 2,194
  • 16
  • 20
16

The HTML5 provides a template element:

contents = $('#template').html();
copy = $('<div id="copy"></div>');
$('body').append(copy.append(contents));

The HTML part:

<html>
  <body>
    <template id='template'>
    </template>
  </body>
</html>

The clone method is not sufficient.

manuel
  • 209
  • 2
  • 3
11

Three more notes on your code:

So your code will look like:

var $template = $("#template").clone();
$template.attr("id", "newid");

$template.appendTo("body");
Community
  • 1
  • 1
Paul Kozlovitch
  • 786
  • 7
  • 12
  • 3
    Because creating jQuery object is a lot of work under the hood(you can take a look in jQuery source) and why do it again, if you already done it and store result in variable? And even if it wasn't so much work, even if it's only cache reading, simply referring what variable already stores is always faster than anything else. – Paul Kozlovitch Feb 02 '15 at 19:51
8

For me clone() didn't work with <template>. Best answer was the one from Manuel, but to generate a JQuery object from template without adding an element as he did, I used this one-liner:

var template = $($("#template").html());

with this html

<html>
 <body>
  <template id='template'>
  </template>
 </body>
</html>
4javier
  • 481
  • 2
  • 7
  • 22
2

You can use the clone() method like so:

template = $('#template').clone();
template.attr('id', 'newid');
template.appendTo('body');

Look at http://api.jquery.com/clone/ for more info.

Tom Walters
  • 15,366
  • 7
  • 57
  • 74
2

The 3-lines solution will work, but I suggest the 1-line short jQuery style solution:

$('#template').clone().attr('id', 'newid').appendTo('body');
Cokegod
  • 8,256
  • 10
  • 29
  • 47