When I run the code below nothing shows up on my webpage and I’m wondering why.
I’m not too sure what i’m doing wrong here. I tried running this through ChatGPT and it said it should work but when I run it the page is left completely blank.
for (let i = 0; i < 49; i++) {
const createDivs = document.createElement('div');
document.body.appendChild(createDivs);
if (i % 2 === 0) {
createDivs.classList.add('set-to-black');
} else {
createDivs.classList.add('set-to-red');
}
}
const setToBlack = document.getElementsByClassName('set-to-black');
for (let i = 0; i < setToBlack.length; i++) {
setToBlack[i].style.backgroundColor = 'black';
setToBlack[i].style.height = '60px';
};
const setToRed = document.getElementsByClassName('set-to-red');
for (let i = 0; i < setToRed.length; i++) {
setToRed[i].style.backgroundColor = 'red';
setToRed[i].style.height = '60px';
};
2
Answers
Uncomment your code, remove the lines that sets the height then add just a tiny bit of CSS and you’re there. Fully annotated example below.
Using CSS Grid you can solve this with one loop.
nth-child
to identify which square should be black/red.square
class, and adding in a colour class depending on whether the iteration index is odd or even.Additional documentation
Template/string literals
:nth-child