$(function () { var appendToDiv = $("#myTable"); var myJSONData = [ { Id: "X", Title: "Square", Color: "Orange", Count: 1 }, { Id: "Y", Title: "Circle", Color: "Red", Count: 2 }, { Id: "Z", Title: "Triagle", Color: "Green", Count: 3 } ]; $.each(myJSONData, function (i, dataRow) { // Make a copy template found within this page var myRowHTML = $("#myRowTemplate").html(); // grab HTML and not the DOM Object so that we can create a "copy" of it; // Replace any "pre-defined variables" via global search and replace. // IMPORTANT we need to do this first before we convert string into DOM object, because some of these "pre-defined variables" may be part of IDs myRowHTML = myRowHTML.replace(/ROWID/g, dataRow.Id + "Row"); myRowHTML = myRowHTML.replace(/FIRSTCELLID/g, dataRow.Id + "Cell"); // Convert string into DOM object var myRow = $(myRowHTML); // Find objects within template to replace values myRow.find(".myTitle").html(dataRow.Title); myRow.find(".myColor").html(dataRow.Color); myRow.find(".myCount").html(dataRow.Count); // Now append our template to final destination appendToDiv.append(myRow); if (i == (myJSONData.length - 1)) { // if last item console.log("Done!"); } }); });
<!-- Template will be "hidden" --> <div id="myRowTemplate" style="display:none;"> <div class="row" id="ROWID"> <div class="col-md-6 myTitle" id="FIRSTCELLID"></div> <div class="col-md-6 myColor"></div> <div class="col-md-6 myCount"></div> </div> </div> <h1><b><a target="_blank" href="https://twitter.com/yesi79">@yesi79's</a> Alternartive to JQuery Template Plugins</b></h1> <p>Right Click and Inspect Element on an Item to see the updated values for ROWID and ITEMID:</p> <div class="container"> <div class="row"> <div class="col-md-6"><b>Name</b> </div> <div class="col-md-6"><b>Color</b> </div> <div class="col-md-6"><b>Count</b> </div> </div> <div id="myTable"></div> </div>
h1 { font-size:24px; margin:0; } /* Placing this here because JFiddle does not load Bootstrap correctly */ .col-md-6 { display: inline-block; width:25%; }