2

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.

6
  • 3
    You should consider a template engine Commented Jul 6, 2016 at 15:47
  • Template engine like Handlebars.js 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. 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? Commented Jul 6, 2016 at 15:49
  • 1
    There is this post that will help you (suggests using innerHTML): stackoverflow.com/questions/11422095/… Commented Jul 6, 2016 at 15:51

2 Answers 2

5

You can try something along these lines:

for(i = 0;i<howeverManyYouNeed;i++)
{
    document.getElementById("parentId").innerHTML += "<div>col"+i+"</div>";
}
Sign up to request clarification or add additional context in comments.

1 Comment

He says he is already doing this currently. But he wants to put it in html.
1

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.com/2015/01/template-strings-html.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.