2

What's the correct way to do the (pseudo) following:

<div id="myTemplate">
  <div id="child1"></div>
  <span id="child2"></span>
</div>


<script>
  var templateCopy = document.getElementById("myTemplate")
  var copy1 = document.createElementFromTemplate(templateCopy);
  document.appendChild(copy1);
</script>

TIA

6
  • I would look at a framework or library. jQuery has templates: api.jquery.com/category/plugins/templates Commented Sep 10, 2011 at 22:59
  • Why? Why not use a templating engine? What are you trying to accomplish? Commented Sep 10, 2011 at 23:00
  • templating engine? to perform a simple function? Seems like overkill. Anyway... I think cloneNode is the function I'm looking for... double checking now... Commented Sep 10, 2011 at 23:02
  • jsfiddle.net/WXgrM/1 this is an example that I found several days ago somewhere here. Commented Sep 10, 2011 at 23:04
  • You shouldn't use id's in a template. When it is copied, you'll have a duplicate id. Commented Sep 10, 2011 at 23:05

4 Answers 4

3

var copy1 = templateCopy.cloneNode(true), beware - id will be copied too.

Sign up to request clarification or add additional context in comments.

1 Comment

yeah, that's what I'm looking for... thanks very much. I can change the id, I believe. I'm a little surprised how many jQuery answers I'm getting for something so straight forward... I have no use or need for jQuery. I'm performing a simple task, I don't want to load a giant framework to accomplish it!
0

I know you can do it in jQuery http://api.jquery.com/clone/

Comments

0

Microsoft has contributed a jQuery by having jQuery Templates plugin. Hope this helps

https://github.com/jquery/jquery-tmpl

Comments

0

jQuery templates do pretty much what you are asking. You can use

  $("elem").tmpl(output)

... And also have string substitutions too.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.