最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Repeat HTML code with plain Javascript - Stack Overflow

programmeradmin3浏览0评论

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
 |  Show 1 more ment

2 Answers 2

Reset to default 5

You 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

发布评论

评论列表(0)

  1. 暂无评论