I'm trying to convert my CSS-grid into a CSV. I found this thread showing how to form the data if I can get it into an array format: How to export JavaScript array info to csv (on client side)?.
Is there a way to select all of the div values in the grid table as an array? Or even better create an array of row arrays
.grid-table {
display: grid;
grid-template-columns: repeat(5, 1fr);
}
<div >
<div>head1</div>
<div>head2</div>
<div>head3</div>
<div>head4</div>
<div>head5</div>
<div>item1</div>
<div>item2</div>
<div>item3</div>
<div>item4</div>
<div>item5</div>
<div>item6</div>
<div>item7</div>
<div>item8</div>
<div>item9</div>
</div>
CodePudding user response:
You can grab all the items using querySelectorAll
and use getComputedStyle
to count the number of columns in each row. see this answer
var computedStyle = getComputedStyle(document.querySelector('.grid-table'))
var columnsCount = computedStyle.getPropertyValue("grid-template-columns").split(" ").length // in our case 5
var container = document.querySelector('.grid-table')
var columns = getComputedStyle(container).getPropertyValue("grid-template-columns").split(" ").length;
var items = document.querySelectorAll('.grid-table div');
var output = []
var row = 0;
items.forEach(function (item, i) {
if (i % columns === 0) {
if (output.length > 0) {
row ;
}
output.push([])
}
output[row].push(item.innerHTML)
});
console.log(output)
.grid-table {
display: grid;
grid-template-columns: repeat(5, 1fr);
}
<div >
<div>head1</div>
<div>head2</div>
<div>head3</div>
<div>head4</div>
<div>head5</div>
<div>item1</div>
<div>item2</div>
<div>item3</div>
<div>item4</div>
<div>item5</div>
<div>item6</div>
<div>item7</div>
<div>item8</div>
<div>item9</div>
</div>