How To Append Html Template Inside A For Loop In Javascript?
I'm trying to dynamically create 100 li's and append a 'template' of html inside of each one. On top of that, I want to dynamically increment the id='Increment' span element by 1 i
Solution 1:
var toAdd = document.createDocumentFragment();
var i=1;
while(i < 101){
var newLi = document.createElement('li');
newLi.id = 'Product'+i;
newLi.className = 'item';
newLi.innerHTML = '<li><divclass="flip-container"ontouchstart="this.classList.toggle(\'hover\');"><divclass="flipper"><divclass="front"><span>'+i+'</span></div><divclass="back"><span>Buy</span></div></div></div></li>';
toAdd.appendChild(newLi);
i++;
}
document.getElementById('currentStore').appendChild(toAdd);
Solution 2:
You can do something like this Fiddle:
Create a function just for readability, note that \ on every row is used for removing the space between rows..
function html_template(index){
return '<divclass="flip-container"ontouchstart="this.classList.toggle(\'hover\');"> \
<divclass="flipper"> \
<divclass="front"> \
<span>'+index+'</span> \
</div> \
<divclass="back"> \
<span>Buy</span> \
</div> \
</div> \
</div>';
}
Change your javascript into this:
var toAdd = document.createDocumentFragment();
for(var i=1; i < 101; i++){
var newLi = document.createElement('li');
newLi.id = 'Product'+i;
newLi.className = 'item';
newLi.innerHTML = html_template(i); //call the function here..
toAdd.appendChild(newLi);
}
document.getElementById('currentStore').appendChild(toAdd);
Post a Comment for "How To Append Html Template Inside A For Loop In Javascript?"