I want to build the markup below by iterating on an array of objects. The structure of the object is also listed below. I need some tips on how to make it clean.
Markup I want to build:
<!--the markup I want to build-->
<div class="pull-left col-xs-4">
<div class="thumbnail">
<div class="caption">
<h5>Crowne Plaza Hotel</h5>
</div>
<img class="img-responsive" src="img/crown-plaza.jpg" alt="Crowne Plaza Hotel">
<div class="caption">
<h3 class="pull-right">
<small>
<s>S$ 275</s>
</small>S$ 275</h3>
<div class="clearfix"></div>
</div>
</div>
</div>
JavaScript:
//the object structure of each data
{
name: "Hotel A",
loc: "Prontera Rd",
dist: 9,
img: "img/rendezvous-hotel.jpg",
price: 350,
deal_price: 350,
currency: "S$",
star_rating: 4
}
function constructDOMFragment(data) {
var fragment = document.createDocumentFragment();
for (var i = data.length - 1; i >= 0; i--)(function(obj) {
var div_container = document.createElement("div");
div_container.className = "pull-left col-xs-4";
var div_thumbnail = document.createElement("div");
div_thumbnail.className = "thumbnail";
div_container.appendChild(div_thumbnail);
var div_caption_top = document.createElement("div");
div_caption_top.className = "caption";
var h5 = document.createElement("h5");
h5["innerHTML" || "textContent"] = obj.name;
div_caption_top.appendChild(h5);
div_thumbnail.appendChild(div_caption_top);
var img = document.createElement("img");
img.className = "img-responsive";
img.src = obj.img;
img.alt = obj.name;
div_thumbnail.appendChild(img);
var div_caption_bottom = document.createElement("div");
div_caption_bottom.className = "caption";
var h3_deal_price = document.createElement("h3");
h3_deal_price.className = "pull-right";
if (obj.price !== undefined && obj.price && obj.price != obj.deal_price) {
var price = document.createElement("small");
var strikethrough = document.createElement("s");
strikethrough["innerHTML" || "textContent"] = obj.currency + " " + obj.price;
price.appendChild(strikethrough);
h3_deal_price.appendChild(price);
}
h3_deal_price.appendChild(document.createTextNode(" " + obj.currency + " " + obj.price));
div_caption_bottom.appendChild(h3_deal_price);
var clearfix = document.createElement("div");
clearfix.className = "clearfix";
div_caption_bottom.appendChild(clearfix);
div_thumbnail.appendChild(div_caption_bottom);
fragment.appendChild(div_container);
})(data[i]);
var clearfix = document.createElement("div");
clearfix.className = "clearfix";
fragment.appendChild(clearfix);
return fragment;
};