Carlos Carlos - 3 years ago 73
Javascript Question

wrap n number of div in one parent using javascript

I have list of html element which has been generated by javascript. Now Every 4 (could be different) should have one parent. The problem is how do we close the div after 4th element.

Here's a snippet (or here's a fiddle):



var x = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"]
var html = '';
for (var i = 0; i < x.length; i++) {
if (i % 3 === 0) {
html += '<div class="parent">';
}
html += '<div class="child">' + x[i] + '</div>'

if (i % 3 !== 0 || i === (x.length - 1)) {
html += '</div>';
}

}

document.getElementById('test').innerHTML = html

.child{ margin: 10px; background: green; float: left; padding: 20px}

<div id="test"></div>




Answer Source

Instead of starting with i=0 in the for loop start with i=1 and end with i <= x.length. With this in place the logic should be straight forward.

Here is the code sample

var x = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"]
var html = '';

for (var i = 1; i <= x.length; i++) {
  if (i % 4 === 1) // if remainder is 1 it means the 1st element of the block, So open new parent
    html += '<div class="parent">';

  html += '<div class="child">' + x[i - 1] + '</div>'

  if (i % 4 === 0) // if remainder is 0 then we have completed 4 elements so close the parent
    html += '</div>';
}

document.getElementById('test').innerHTML = html
.child {background: yellow;padding: 20px;display: block; flex: 1;}
.parent {border: 2px solid green;margin: 10px;display: flex;}
<div id="test"></div>

Edit

  if (i % 4 === 0 || i === x.length) // if remainder is 0 then we have completed 4 elements so close the parent
    html += '</div>';
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download