Search code examples
jquery

Create element from template element?


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?


Solution

  • Clone the object:

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