## Getting neighboring squares in a grid

Here's an HTML example of a 3x3 grid. Notice that each row has a data-y attribute, and each square has a data-x attribute, which are used in the JavaScript.

```<div id="grid">
<div class="row" data-y="0">
<div class="square" data-x="0"></div>
<div class="square" data-x="1"></div>
<div class="square" data-x="2"></div>
</div>
<div class="row" data-y="1">
<div class="square" data-x="0"></div>
<div class="square" data-x="1"></div>
<div class="square" data-x="2"></div>
</div>
<div class="row" data-y="2">
<div class="square" data-x="0"></div>
<div class="square" data-x="1"></div>
<div class="square" data-x="2"></div>
</div>
</div>
```

Here's a JavaScript example of getting neighboring squares for a clicked square. Notice that there is a helper function, which eliminates duplicate code.

```var rows = document.querySelectorAll(".row"); // array of rows

function clickSquare() {
var squareToLeft = getNeighbor(this, -1, 0); // will be null if square is on left edge
var squareToRight = getNeighbor(this, 1, 0); // will be null if square is on right edge
var squareAbove = getNeighbor(this, 0, -1); // will be null if square is on top edge
var squareBelow = getNeighbor(this, 0, 1); // will be null if square is on bottom edge
}

function getNeighbor(square, xAmount, yAmount) {
var row = square.parentElement; // get the row of the square

var y = row.getAttribute("data-y"); // get the y coordinate of the square
y = parseInt(y, 10); // convert y from a string to an integer

var neighborRow = rows[y + yAmount]; // get the row of the neighbor square

if (neighborRow == null) {
return null; // the neighbor row is beyond the edge, so there is no neighbor square
}
else {
var x = square.getAttribute("data-x"); // get the x coordinate of the square
x = parseInt(x, 10); // convert x from a string to an integer

return neighborRow.children[x + xAmount]; // return the neighbor square
}
}
```