'Is there a way to detect which CSS grid column and row an element is in using javascript?

Is there a way to dynamically detect in javascript which grid column and row an element is in, in a CSS grid?

I have a grid that I set up with three breakpoints so that it either has 4, 3, or 2 columns.

What I want to do is if a user clicks in a cell, dynamically overlay a new element in the cell immediately to the right of the cell that was clicked, except if it's in the right-most column, in which case the overlay element will go in the cell to the left.

I know I can use grid-column and grid-row to specify the cell I want to put the new thing in, but in order to be able to use that, I need to know the column and row of the cell that was clicked.

How can I dynamically determine that?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source