How to iterate through DOM elements changing id with Javascript

yotube
0

Issue

I have 36 divs with ids id="square-1", "square-2", etc., framed in a grid 6x6 container. I want them to be all square and be the size of each square of the grid. I want to make a function to add css to each of them to determine their position in the grid. In my mind I can do something to iterate through them with a for loop and apply "gridColumn = "a/b"", where a and b are relative to the i in the for loop, so that I don't have to specify that 36 times in the css document. Is this even possible? Does it make sense? Very beginner...

    <div class="div-container">
<div id= "square-1"></div>
<div id= "square-2"></div>
<div id= "square-3"></div>
<div id= "square-4"></div>
<div id= "square-5"></div>
<div id= "square-6"></div>
<div id= "square-7"></div>
etc...
</div>

Solution

Keeping track of elements by a CSS property is fragile. If you are using JavaScript, then let it do the heavy lifting. For instance, instead of hard coding 36 <div> with ids, make a <div> on each iteration of a loop. In the example below, the container is a <main> and each sub-box is a <section>. Each <section> is given a CSS property of order and a corresponding number and an id: "sq"+ a corresponding number. The order property applies to the order in which a flex item appears within a flex container.



const box = document.querySelector('main');

for (let i = 0; i < 36; i++) {
const sec = document.createElement('section');
sec.style.order = i;
sec.id = `sq${i}`;
box.append(sec);
}

html {
font: 300 5vmin/1 Consolas
}

main {
display: flex;
flex-flow: row wrap;
width: 12rem;
height: 12rem;
border: 1px solid red
}

section {
width: 2rem;
height: 2rem;
outline: 1px dashed blue
}

<main></main>





Answered By - zer00ne

Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !
To Top