javascripthtmlforeach

Javascript - Creating divs to a foreach loop every x times


I have a foreach loop and I need to wrap a div with className='row' around the output of the data every 2 loops.

this is my loop

function getUsers(){
usersjson.users.forEach(function (user,counter) {
//create a DOM element
var div = document.createElement('div');
//add class row every 2 loops
div.className = 'row';
//names
var names = "<p>" + user.first_name +' '+user.last_name+"</p>";
//append to html
div.innerHTML = names;
$('.users_list').append(div);
});
}

This is how it should look like

<div class="row">
<p>John Doe</p>
<p>Jane Doe</p>
</div>

<div class="row">
<p>Marcy Doe</p>
<p>Alfred Doe</p>
</div>

<div class="row">
<p>Judy Doe</p>
<p>Lana Doe</p>
</div>

//...etc

Solution

  • Can you try this:

    function getUsers(){
    
        let names = ""
        usersjson.users.forEach(function (user,counter) {
    
            names = names + "<p>" + user.first_name +' '+user.last_name+"</p>";
            if(counter % 2  == 0) {
                $('.users_list').append(`<div class="row">${names}</div>`);
                names = ""
            } 
    
        });
    }