HTML example of a 3×3 grid. Each row has a row class, which is
used in the JavaScript.
<div id="grid">
<div class="row">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>
<div class="row">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>
<div class="row">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>
</div>
JavaScript example of getting neighbors of a clicked square.
function clickSquare() {
let squareToLeft = getNeighbor(this, -1, 0) // null if square on left edge
let squareToRight = getNeighbor(this, 1, 0) // null if square on right edge
let squareAbove = getNeighbor(this, 0, -1) // null if square on top edge
let squareBelow = getNeighbor(this, 0, 1) // null if square on bottom edge
}
function getNeighbor(square, xDiff, yDiff) {
// array of rows
let rows = document.getElementsByClassName(`row`)
let row = square.parentElement // row of square
let y // y coordinate of square, set below
let x // x coordinate of square, set below
// loop through rows to determine y
for (let i = 0; i < rows.length; i++) {
if (rows[i] == row) {
y = i // found matching row, so set y
}
}
// loop through squares in row to determine x
for (let i = 0; i < row.children.length; i++) {
if (row.children[i] == square) {
x = i // found matching square, so set x
}
}
// row of neighbor square
let neighborRow = rows[y + yDiff]
if (neighborRow == null) {
// row is beyond edge, so no neighbor square
return null
}
else {
// if x + xDiff is beyond edge, will be null
return neighborRow.children[x + xDiff]
}
}