A grid is implemented using the CSS flexbox. Example:
The number of rows in this example is 4 because I fixed the container width for demo purposes. But, in
While you can calculate which element you're looking for, I suggest you search for the element below. The benefit of this is that it would even work if your elements dont have the same width.
So lets think about the attributes of the element below are. Essentially its the first element with a higher offsetTop and the same offsetLeft. You can do something like this to find the element ontop:
const active = document.querySelector('.item.active');
const all = [...document.querySelectorAll('.item')]
const below = all
.filter(c => c.offsetTop > active.offsetTop)
.find(c => c.offsetLeft >= active.offsetLeft)
const ontop = [...all].reverse()
.filter(c => c.offsetTop < active.offsetTop)
.find(c => c.offsetLeft >= active.offsetLeft)