const wp = document.querySelector('.wrapper')
const config = {
data :[{"Name":"John","Age":25,"Gender":"Male"},{"Name":"Emily","Age":33,"Gender":"Female"},{"Name":"Michael","Age":42,"Gender":"Male"},{"Name":"Sarah","Age":29,"Gender":"Female"},{"Name":"William","Age":37,"Gender":"Male"},{"Name":"Samantha","Age":26,"Gender":"Female"},{"Name":"Benjamin","Age":48,"Gender":"Male"},{"Name":"Elizabeth","Age":31,"Gender":"Female"},{"Name":"David","Age":45,"Gender":"Male"},{"Name":"Olivia","Age":28,"Gender":"Female"}],
colors : ['255,0,0', '0,255,0', '0,0,255'],
cols : 3,
rows : 3,
lastSelectedColumn: null
}
function getSelectorTexts(column, columns, rows, color){
const index = (column + 1) % columns
const i = index ? `+ ${index}` : ''
return [
`.wrapper div:nth-child(${columns}n${i})`,
`.wrapper div:nth-child(${column + 1})`,
`.wrapper div:nth-child(${(rows-1) * columns + column + 1})`
]
}
function selectColumn(column){
const stylesheet = document
.querySelector('style[title="grid-wrapper"]')
if (!stylesheet || column === null) return
const rules = getSelectorTexts(column, config.cols,
wp.children.length / config.cols, config.colors[column])
let i = 2
for (const rule of rules){
stylesheet.sheet.rules[i++].selectorText = rule
}
}
document.querySelector('button').onclick = function(){
if (config.rows > config.data.length -1) return
Object.values(config.data[config.rows++])
.map(e => Object.assign(document.createElement('div'),{textContent: e}))
.forEach(e => wp.appendChild(e))
selectColumn(config.lastSelectedColumn)
}
wp.onclick = function({target}){
if (target.className !== "") return
const index = Array.from(wp.children).indexOf(target)
selectColumn(config.lastSelectedColumn = index % config.cols)
}
<style title="grid-wrapper">
.wrapper {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
width: fit-content;
background: #e5e5e5;
color: black;
margin: 10px;
}
.wrapper div {
padding: 5px;
border-width: 3px;
border-color: transparent;
box-shadow: 1px 1px 1px black;
}
.rule1 {
border-width: 0px 3px 0 3px;
border-color: rgb(0, 0, 255);
border-style: solid;
background: rgba(0, 0, 255, .1);
}
.rule2 {
border-width: 3px 3px 0 3px;
border-color: rgb(0, 0, 255);
}
.rule2 {
border-width: 0 3px 3px 3px;
border-color: rgb(0, 0, 255);
}
</style>
<p>Please, select a column, and click on `Add`</p>
<div class="wrapper">
<div>Name</div>
<div>Age</div>
<div>Gender</div>
<div>John</div>
<div>25</div>
<div>Male</div>
<div>Emily</div>
<div>33</div>
<div>Female</div>
<div>Michael</div>
<div>42</div>
<div>Male</div>
</div>
<button>Add</button>