Is there a way to have html/javascript code to repeat html-code? Basically, I need to use plain javascript and at the same time I need to build html elements in a for loop. So in html I can have:
<div>col1</div>
<div>col2></div>
<div>col3</div>
The problem is that there can be several sets of the above html code. What I'm doing now is to write html inside the javascript code. I would like to make it cleaner and have the html structure where it belongs, which is in the html-page.
Is there a way to have html/javascript code to repeat html-code? Basically, I need to use plain javascript and at the same time I need to build html elements in a for loop. So in html I can have:
<div>col1</div>
<div>col2></div>
<div>col3</div>
The problem is that there can be several sets of the above html code. What I'm doing now is to write html inside the javascript code. I would like to make it cleaner and have the html structure where it belongs, which is in the html-page.
Share Improve this question edited Jul 6, 2016 at 15:50 Olivier De Meulder 2,5013 gold badges26 silver badges32 bronze badges asked Jul 6, 2016 at 15:46 oderflaoderfla 1,7974 gold badges29 silver badges58 bronze badges 6- 3 You should consider a template engine – Sander Sluis Commented Jul 6, 2016 at 15:47
- Template engine like Handlebars.js – chf Commented Jul 6, 2016 at 15:47
- Well I now that it would solve the problem. Thing is that Im in a project where I need to use plain javascript. – oderfla Commented Jul 6, 2016 at 15:47
- 1 @oderfla a template engine is plain javascript :) I guess what you mean is that you can't use an external library? – Sander Sluis Commented Jul 6, 2016 at 15:49
- 1 There is this post that will help you (suggests using innerHTML): stackoverflow./questions/11422095/… – Sander Sluis Commented Jul 6, 2016 at 15:51
2 Answers
Reset to default 5You can try something along these lines:
for(i = 0;i<howeverManyYouNeed;i++)
{
document.getElementById("parentId").innerHTML += "<div>col"+i+"</div>";
}
I would suggest you write your own minimal templating library if you're using ES-6 templates. See this blogpost on how to do that: http://www.2ality./2015/01/template-strings-html.html