I want to change the background colour of the body element. When I tried with the first, it won’t work. But when I tried with the second, it worked perfectly. I want to know the reason.
let x = document.getElementsByTagName("BODY")[0].style.backgroundColor
function change() { x = "red"; }
let x = document.getElementsByTagName("BODY")[0]
function change() { x.style.backgroundColor = "red"; }
2
Answers
In your firts example, you’re assigning the background color of the to the variable x but modifying x doesn’t affect the element because it simply reassigns x, without updating the actual style of the page.