Creating a 3x3 grid in CSS

Kirupa’s video is the isssue here:

Now how to access the innerHTML etc of a specific element in the grid from Javascript? That is the challenge. It seems the grid layout uses a template to place items, but is there a way to easily access the items from Javascript .
One scenario I imagine is where you might want to use the location of the item within the grid, but if you change the layout so that it changes position, how does one make the code remain valid or responsive to the CSS change?

You can easily access the elements via the parent:

let parent = document.querySelector('.parent');
let child1 = parent.children[0];

you can loop

let nodes = parent.children
for(let child of nodes){

for CSS you can use the nth of child e.g.
.parent:nth-child(1) // child one, CSS is not zero index


If you are trying to figure out the element via a mouse action like a click, this article may help simplify this: Handling Events for Many Elements | KIRUPA

A bookkeeping trick: If you know for sure that you’ll have 3x3 items only, you can add more class values or data- attributes to each of the elements that better describe the column/row.

1 Like

There’s a new CSS selector that’s spec’d but nobody’s implemented:

15.2. :nth-col() pseudo-class

The :nth-col(An+B) pseudo-class notation represents a cell element belonging to a column that has An+B-1 columns before it, for any positive integer or zero value of n.

I think this will really be a game changer for CSS Grid.

The other one is CSS Subgrid but I think all the browsers have dropped the ball on that one because they have implemented display: contents