+ 4
Js body background
I dont know what do in the js the body element background e.g. html * <body id=“body”> … </body> Js * function time() { let body = document.getElementById(“body”); body.style.background = “red”; } setTimeout(time, 2000)
3 odpowiedzi
+ 2
Suspic*
Solved it
Your JS code is running fastly then loading of your html code
so if your html did not loaded first. So there was no body element has created in your html. So document.getElementById() found nothing.
Because of this your body variable has no id in it.
It's Null.
So it is throwing errors.
See below code and read comments
https://code.sololearn.com/Wn9GLrw2LzTV/?ref=app
+ 5
const clr = ["red", "green", "blue"];
const b = document.getElementsByTagName("body");
let idx, rnd;
function time() {
idx = Math.floor((Math.random() * clr.length) + 0);
rnd = clr[idx]; // console.log(clr[idx]);
b[0].style.backgroundColor = rnd;
}
// 1 sec
setInterval(time, 1000);
https://code.sololearn.com/WgoG7k4Xo62v
Good Luck
+ 2
Not work the ‘body.style.background = “red”’