Димитр,
<!DOCTYPE HTML>
<html>
<head>
<title>Untitled</title>
<meta charset="utf-8">
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.wrapper {
display: grid;
width: 220px;
height: 220px;
}
#grid {
display: grid;
grid-template-columns: repeat(var(--columns, 5), auto);
grid-template-rows: repeat(var(--rows, 5), auto);
width: 220px;
height: 220px;
}
#grid>div {
height: 42px;
width: 42px;
background-color: #38d929;
border: solid 1px white;
text-align: center;
line-height: 42px;
}
</style>
</head>
<body>
<div class="wrapper">
<div id="grid"></div>
</div>
<script>
let rows = 5;
let columns = 8;
grid.style.setProperty('--rows', rows);
grid.style.setProperty('--columns', columns);
const arr = Array.from({
length: rows
}, _ => Array.from({
length: columns
}, _ => {
const o = document.createElement('div')
grid.insertAdjacentElement('beforeend', o)
return 0;
}))
let divs = Array.from(document.querySelectorAll('#grid > div'));
grid.addEventListener('click', e => {
const o = e.target.closest('#grid > div');
if (!o) return;
let ii = divs.indexOf(o);
const r = ii / columns | 0;
const c = ii % columns;
for (let i = r - 1; i <= r + 1; i++) {
if (i < 0 || i == rows) continue
for (let j = c - 1; j <= c + 1; j++) {
if (j < 0 || j == columns) continue
if (i === r && j === c) continue
arr[i][j] = 3;
let k = i * columns + j;
divs[k].textContent = 3
}
}
})
</script>
</body>
</html>