Demonstrate appending manually using jQuery
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"></ul>
CSS
body { font-family:Arial,Sans-Serif; }
.template { display:none; }
b { color:Red; }
JavaScript
$(document).ready(function() {
var $list = $("ul#listItems");
$.each(items, function (idx, item) {
var $li = $("<li>").attr("class", "my-item").data("index", idx);
$("<h2>").text(item.name).appendTo($li);
var $p = $("<p>");
$("<span>This is an example for: <b></b>, showing how to construct html fragments using jQuery</span>").find("b").text(item.name).end().appendTo($p);
$("<a>Click to visit my homepage</a>").attr("href", item.homeURL).appendTo($p);
$li.append($p).append($("<h3>").text(item.test)).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" }
];