Last Updated: February 25, 2016
· alexanderbrevig

Copy and append elements with EASE, fill with data from JSON hash

So, time and time again I've had the simple need to do this:

1) Find a template element
2) Copy the element
3) Fill the copy with new data
4) Append the copy as the last sibling of the template element

So, I wrote a jQuery plugin to do exactly that.

Given the following HTML:

<div id="container">
  <div class="template" style="display:none;">
    <h1 class="header">Header</h1>
      <li class="line0">Line 0</li>
      <li class="line1">Line 1</li>
      <li class="line2">Line 2</li>

Create and append a copy of the .template to the #container by this jQuery call:

$("#container").copyAndAppend("template", {
    "header": "Header from js",
    "line0":"Line 0 from js",
    "line1":"Line 1 from js",
    "line2":"Line 2 from js"

Will result in this HTML:

<div class="" style="display: block;">
  <h1 class="header">Header from js</h1>
    <li class="line0">Line 0 from js</li>
    <li class="line1">Line 1 from js</li>
    <li class="line2">Line 2 from js</li>


Say Thanks