Is there a way to get the element that is visually underneath or above or left or right a certain element?

I am working on simple game (classic number game) with JavaScript
in which a container div with display Flex contains 9 divs
8 divs are blue with numbers inside from 1 to 8 and 1 div is white without any content
each time the page loaded the divs are ordered randomly
image of the game

and the empty div is placed randomly too.

the mission is to rearrange the numbers from 1 to 8 that when you click on any div that is visually neighbor (above, beneath, left or right)

to the empty div
they are switch their positions
in this image the divs that are allowed to move are 4,7,5
How I can make it with javaScript or jquery ?

here is my code:

$(document).ready(function(){
  var arr = [];
  
  for(i=1;i<9;i++)
  {
    arr.push(i);
  }
  
  arr.push("");

  function shuffleArray(array) 
  {
    for (let i = array.length - 1; i > 0; i--) 
    {
      const j = Math.floor(Math.random() * (i + 1));
      [array[i], array[j]] = [array[j], array[i]];
    }
  }
  
  shuffleArray(arr);

  for(i=0;i<9;i++)
  {
    divContent.innerHTML += "<div class='tile'>"+arr[i]+"</div>"
  }

  var tile = document.getElementsByClassName("tile");

  var n = 0;

  while (n < tile.length) 
  {
    if (tile[n].textContent != (n+1))
      break;
    
    tile[n].style.color = "yellow";
    n++;
  }

  for(i=0;i<tile.length;i++)
  {
    if(!tile[i].textContent)
    {
      tile[i].style.backgroundColor  = "#fff";
      tile[i].classList.add("whitt");
    }
    tile[i].style.color = "#fff";
  }

  $('.tile').click(function (evt) {
    var $div = $(evt.target).closest('.tile');
    $div.next('.tile').after($div).animate({opacity: 0.9, top:'100'}, 500 );

    for(i=0;i<tile.length;i++)
    {
      if(!tile[i].textContent)
      {
        tile[i].style.backgroundColor  = "#fff";
        tile[i].classList.add("whitt");
      }
      tile[i].style.color = "#fff";
    }

    n = 0;
    
    while (n < tile.length) 
    {
      tile[n].style.color = "#fff";
      if (tile[n].textContent != (n+1)) 
        break;
      tile[n].style.color = "yellow";
      n++;
    }
  });
});
.flexDiv{
  display:flex;
  flex-wrap: wrap;
  width:310px;
  border:1px solid black;
}
.tile{
  position:relative;
  background:#08088A;
  text-align:center;
  width:29%;
  margin:1px;
  font-size:75px;
  font-weight:bold;
  color:#fff;
  padding:5px;
}
.wh{
  background:#fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<div id="divContent" class="flexDiv"></div>