简体   繁体   中英

Repeat HTML code with plain Javascript

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM