Skip to content
Advertisement

Generate html in for each with closing tag every 4 loop

I’m trying to generate the following html :

JavaScript

So I tried the following :

JavaScript
JavaScript

But doesn’t output the desired result

Advertisement

Answer

Try like below. And check changes with comment.

There are two changes in your code.

  1. You need to open your row div with i%4 == 0 and close it with i%4 == 3.
  2. Once each loop complete you should check if (json.length - 1) % 4 != 3 then need to add </div>

JavaScript
JavaScript

Old version

  1. Initialize add_html with opening row div.
  2. When i % 4 == 3 which means it is forth index add closing div and open a new one.
  3. Once each loop completes then add closing div.

Note – This has one bug. It will add extra <div class='row'></div> when json array is of json.length % 4 == 0 .

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement