If I use grid-template-columns: repeat(3, 1fr) to place a number of HTML elements into a 3-column grid, is it possible to find an element's column with JavaScript? Some of the elements span multiple rows as well, so the element's index won't necessarily match its column.
For example:
const myElement = document.querySelector('div:nth-child(5)');
myElement.style.background = '#f00';
const columnIndex = 1; // How do I find this?
console.log('myElement is in column ' + columnIndex);
.grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-gap: 30px;
}
.item,
.item-large {
padding: 30px;
background: #3cf;
}
.item-large {
grid-row: span 2;
}
<div class="grid">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item-large"></div>
<div class="item">Which column am I in?</div>
<div class="item-large"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
What I have done here is loop through all elements, and every time the left position increases and is less than my elements position, I increase a counter to keep track of the column.
I've also modified snippet here to make a little bit more interactive. If you click the div's it re-selects and shows new column number..
var myElement = document.querySelector('div:nth-child(5)');
const allElements = document.querySelector('.grid').querySelectorAll('div');
//myElement.style.background = '#f00';
myElement.classList.add('item-found');
function showFound() {
let maxcolpos = -1, colposCount = 0;
for(elem of allElements) {
let l = elem.getBoundingClientRect().left;
if (l > maxcolpos) {
maxcolpos = l;
if (myElement.getBoundingClientRect().left > l) colposCount ++;
}
}
const columnIndex = colposCount + 1; //zero based, leave +1 if you want 0 based
myElement.innerText = 'Column = ' + columnIndex;
}
showFound();
document.querySelector('.grid').addEventListener("click", function(e) {
if (e.target && !e.target.matches(".grid")) {
myElement.classList.remove('item-found');
myElement.innerText = '';
myElement = e.target;
myElement.classList.add('item-found');
showFound();
}
});
.grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-gap: 30px;
}
.item,
.item-large {
padding: 30px;
background: #3cf;
}
.item-large {
grid-row: span 2;
}
.item-found {
background-color: red;
}
<div class="grid">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item-large"></div>
<div class="item"></div>
<div class="item-large"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With