Home > Software engineering >  Why is this html append structured differently than the array structure
Why is this html append structured differently than the array structure

Time:09-28

I have two for loops which builds my html structure.

The outer loop builds each row '<div class="row">' before the code jumps into the nested for loop which builds each column in the row '<div class="col-sm-1">' data[k].value '</div>' before the row-div is closed in the outer loop.

var i;
var n;
var k = 0;

for (i = 0; i < createRows; i  ) {
    htmlArray.push('<div class="row">')
    console.log("creating row")
    for (n = 0; n < variableAmount; n  ) {
        htmlArray.push('<div class="col-sm-1">'   data[k].value   '</div>')
        k  
    }
    htmlArray.push('</div>')
    console.log("ending row")
}
console.log(htmlArray)
$("#wrapper").append(htmlArray);

The console.log(htmlArray) is showing the expected output and structure which is row containing all the col-sm-1 divs, before building a new row div, but when the array is appended to #wrapper I get a structure similar to this:

<div class="row"></div>
<div class="col-sm-1"></div>
<div class="col-sm-1"></div>
<div class="col-sm-1"></div>

Where the row div is closed without containing any column div.

Wanted structure from console.log of htmlArray:

console.log

CodePudding user response:

Maybe the problem is you append an array. You can use Array.join it to build the final HTML structure.

const finalHTML = htmlArray.join('');
$("#wrapper").append(finalHTML);

  • Related