I'm trying to create a divs table using javascript. Here is my code.
var data = ['a', 'b', 'c', 'd', 'e'];
var html='';
data.forEach((item, i) => {
if (i % 2 == 0)
html = `<div >`;
if (i % 2 == 0)
html = `<div >${item}</div>`;
if (i % 2 != 0)
html = `<div >${item}</div>`;
if (i % 2 == 0)
html = `</div>`;
html =`<div ></div>`;
})
console.log(html);
the output that I get is
<div >
<div >a</div>
</div>
<div ></div>
<div >b</div>
<div ></div>
<div >
<div >c</div>
</div>
<div ></div>
<div >d</div>
<div ></div>
<div >
<div >e</div>
</div>
<div ></div>
But my target Is something like this, in terms of the table. have a 2 columns table.
When coming to div, the first column is going to be <div > and 2nd being <div >, the new row seperator will be <div ></div>. My expected output is as below.
<div >
<div >a</div>
<div >b</div>
</div>
<div ></div>
<div >
<div >c</div>
<div >d</div>
</div>
<div ></div>
<div >
<div >e</div>
</div>
<div ></div>
Please let me know how Can I achieve this.
Thanks
CodePudding user response:
Why not just do it in a for loop and loop by 2? That way you do not have to worry about closing the tags.
const makeRow = (col1, col2) => {
const col2HTML = col2 ? `<div >${col2}</div>` : '';
return `
<div >
<div >${col1}</div>
${col2HTML}
</div>
<div ></div>`;
};
var data = ['a', 'b', 'c', 'd', 'e'];
var html='';
for(let i=0; i< data.length; i =2) {
html = makeRow(data[i], data[i 1]);
}
console.log(html);
If you really want to do it your way, you have to add a check to see if you are at the end of the array.
var data = ['a', 'b', 'c', 'd', 'e'];
var html='';
data.forEach((item, i, arr) => {
if (i % 2 == 0)
html = `<div >\n`;
if (i % 2 == 0)
html = ` <div >${item}</div>\n`;
if (i % 2 != 0)
html = ` <div >${item}</div>\n`;
if (i % 2 != 0 || i === arr.length - 1) {
html = `</div>\n`;
html =`<div ></div>\n`;
}
})
console.log(html);
CodePudding user response:
The easiest way is to use CSS Grids
const data = ['a', 'b', 'c', 'd', 'e'];
const container = document.querySelector('#container');
for (const datum in data) {
let div = document.createElement('div')
div.innerText = datum;
container.append(div);
}
#container {
display: grid;
grid-template-columns: 1fr 1fr;
}
<div id="container"></div>
CodePudding user response:
It's probably easier to accomplish if you just loop through the array in 2-big steps.
var data = ['a', 'b', 'c', 'd', 'e'];
var html='';
for (let i = 0; i < data.length; i = 2){
html = `<div >\n`;
if (i < data.length - 1){
html = `<div >${data[i]}</div>\n`;
html = `<div >${data[i 1]}</div>\n`;
}else if (i = data.length - 1){
html = `<div >${data[i]}</div>\n`;
}
html = `</div>\n`;
html =`<div ></div>\n`;
}
console.log(html);
