Demonstrate appending via a template
Try hard not to add an "id" attribute to appended DOM fragments because id's must be unique on a page. In any case, it is often better to put unique information within a custom data field instead
by alano
HTML
<ul id="listItems">
<li class="template"> <!-- mark this li as our template, so it will be hidden -->
<h2></h2>
<p>
<span>This is an example for: <b></b>, showing how neat it is to use templates when appropriate.</span>
<a>Click to visit my homepage</a>
</p>
<h3></h3>
</li>
</ul>
CSS
body { font-family:Arial,Sans-Serif; }
.template { display:none; }
b { color:Red; }
JavaScript
$(document).ready(function() {
var $template = $("li.template"); // I am using a $ prefix to show contents is a jQuery selection
var $list = $("ul#listItems"); // take a copy to speed future references
$.each(items, function (idx, item) {
var $li = $template.clone();
$("h2", $li).text(item.name);
$("b", $li).text(item.name);
$("a", $li).attr("href", item.homeURL);
$("h3", $li).text(item.test);
// add new (or empty) the class name to remove "template" class,
// and add custom Data, then append to main list
$li.attr("class", "my-item").data("index", idx).appendTo($list);
});
});
//Example datasource...
var items = [
{ name: "jw", test: "abc1", homeURL: "http://blah1.com" },
{ name: "John", test: "abc2", homeURL: "http://blah2.com" },
{ name: "Alan", test: "abc3", homeURL: "http://blah3.com" }
];