Js body background | Sololearn: Learn to code for FREE!


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/1/2022 6:19:46 AM

Fishy (◍•ᴗ•◍)

3 Answers

New Answer


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


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


Not work the ‘body.style.background = “red”’