Is it possible to count columns in each grid row? Rows can be dynamic.
let grid = document.querySelector('.grid');
let columns = document.querySelectorAll('.column');
let button = document.querySelector('button');
.grid {
display: grid;
grid-template-columns: auto auto auto;
justify-items: start;
grid-gap: 10px;
}
.grid div {
border: 1px solid #000;
width: 100%;
}
.grid > *:nth-child(3n-1):nth-last-of-type(1) {
border-color: red;
grid-column: span 2;
}
.grid > *:nth-child(3n-2):nth-last-of-type(1) {
border-color: red;
grid-column: span 3;
}
.grid > *:nth-child(3n-1) {
justify-self: center;
}
.grid > *:nth-child(3n) {
justify-self: end;
}
.result {
border: 1px solid black;
margin: 10px 0;
}
button {
margin: 40px 0;
}
p {
color: green;
}
<div class="grid">
<div class="column">1</div>
<div class="column">2</div>
<div class="column">3</div>
<div class="column">4</div>
</div>
<br />
Row 2
<div class="grid">
<div class="column">1</div>
<div class="column">2</div>
</div>
<br />
<div class="result">
<p>Row 1:</p>
<small>Columns:</small><br />
</div>
<div class="result">
<p>Row 2:</p>
<small>Columns:</small><br />
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Stackblitz: https://stackblitz.com/edit/js-1hzwpx?file=index.html
CodePudding user response:
Use querySelectorAll
to select all elements with class column
, then get the length of the NodeList:
const columns = document.querySelectorAll('.grid .column').length
console.log(columns)
<div class="grid">
<div class="column">1</div>
<div class="column">2</div>
<div class="column">3</div>
<div class="column">4</div>
</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Here is a solution, I added an id to the first grid tag:
Row 1
<div class="grid" id="grid-1">
<div class="column">1</div>
<div class="column">2</div>
<div class="column">3</div>
<div class="column">4</div>
</div>
const grid1 = document.getElementById('grid-1');
// logs the number of columns in the first grid
console.log(grid1.children.length)
Just adapt it to your need.