I am wondering why sometimes I can change the webpage background color and sometimes I can't. For example, in some sites I just type in document.body.bgColor = "red" in the chrome console, and the background color changed temporarily. However, in the other sites like StackOverFlow, this doesn't work. Since my browser has already loaded the page, I should be able to change how to displays it locally. Why not? Thank you
In Chrome you can use the DOM inspector to look at the computed style of the body and also the inheritance / overriding of CSS rules that result in this computed style.
If you set document.body.style.backgroundColor
(not the bgColor
property) you'll see that you can actually change the background color here. It all depends on whether there is another rule somewhere else with higher specificity or not. The DOM inspector will tell you whether that's the case.
CSS is your answer. Try
document.body.style.background="red";
CSS styles supersede element properties.
If you do that, the background will change here too. But as you can see with a DOM Inspector, the background isn't the thing which you really see. This is a div
called container
. If you change the background of this div, you'll see the changes
Edit: Ohh i see the container is transperent. So use document.body.style.backgroundColor
then it will work. :)
You can always set the color of the body background. However, that does not necessarily reflect the background of the current view. Moreover, if there are more specific definitions in place for an element than the definition you impose, they will still be used. So, there is no "why not" because you are correct: you can always change the page locally.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With