Hi coders,
Recently I’m doing this color game that i found in this article on FCC:
I have done HTML and CSS files,but I have some difficult with JS file:
The first goal is to put the colors I put inside an array into squares.
var colors = ["rgb(197,34,14)", "rgb(0,29,164)", "rgb(129,1,253)","rgb(196,161,94)","rgb(123,66,53)","rgb(17,103,22)"]; //set colors
var squares = document.querySelectorAll(".square");//select elements with class .square
for(i=0; i<squares.length; i++){
console.log(squares.style.backgroundColor = colors[i]); //Used console.log to print in console in browser
}
When load page didn’t show a result and left squares white.
Here there is also HTML file:
What does the console log say on your browser in your for loop? It might say that it can’t read backgroundColor of undefined, because you’re not specifying which square out of the list to apply the background color to, as it’s taking in that entire node list.
Try accessing each individual square by doing this
squares[i].style.backgroundColor = colors[i]
and see if that changes the colors of each square.
digita o incolla il codicvar squares = document.querySelector(".square");//select elements with class .square
for(var i=0; i<squares.length; i++){
console.log(squares[i].style.backgroundColor = colors[i]);
}
now console give me this error:
Uncaught TypeError: Cannot read property ‘length’ of null
My doubt is for the “square” class does not have a length and that the “square” class is located inside another div therefore I have to take in the querySelector id container and then loop with for its length?
Did you declare your squares variable using at lease var or const? An issue that could be happening as well is that you’re not selecting all div elements with the class of square, since you are using querySelector, which only selects one element. You would want to use querySelectorAll, to get all elements with a particular class name.
Change it to this and see if it works
var squares = document.querySelectorAll('.square')
Preferably I would change var to const to avoid any potential issues in the future.
On VSCode is your javascript file linked in your HTML file?
Edit: NVM I supposed it would be linked if you’re getting those error messages. What’s does your JS file look like? Does it differ from the original one you posted?
Just looked over your html file again, try moving your script tag for your JS to the bottom, that’s where you would generally put any js files, just right before the closing body tag.
Let me know if that works for ya! I believe you’re getting the error message of null, because when it loads your html file, it reads it from top to bottom, and loads your script tag first, before any of the actual html that you are targeting, hence why it can’t be found.