0

I need to be able to set the background color of a div back to it's original state. I can store it in a variable and recall it, but was wondering why I can't use "initial". Is that now what it's for... to set a css property back to it's initial state?

Thanks in advance.

testDiv.style.background = "red";

//Shouldn't this turn it back to it's original state of yellow?
testDiv.style.background = "initial";
#testDiv{
  background-color: yellow;
  width:40px;
  height:40px;
}
<div id="testDiv"></div>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415
dmperkins74
  • 157
  • 3
  • 10

2 Answers2

0

You're setting initial as the value of the style.background property of the element - that means that it will override whatever the default background color is from the CSS that selects the element. If you want to reset the background property to what's specified by the CSS, use removeProperty instead, to completely remove the property that was Javascript-set, so that the page's CSS regains the highest priority:

testDiv.style.background = "red";
testDiv.style.removeProperty('background');
#testDiv{
  background-color: yellow;
  width:40px;
  height:40px;
}
<div id="testDiv"></div>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

As stated in the documenation:

The initial CSS keyword applies the initial (or default) value of a property to an element. It can be applied to any CSS property.

And

The initial value of a CSS property is its default value, as listed in its definition table.ref

So unlike you think, initial will put the initial value before you set your background-color and it's not the value you set.


Since JS add inline style you can simply delete that style to get back to the yellow color without extra variable as your style remain defined but is simply overridden:

testDiv.style.backgroundColor = "red";

//empty the style attribute
testDiv.style="";
/*OR
testDiv.style.backgroundColor="";
*/
#testDiv{
  background-color: yellow;
  width:40px;
  height:40px;
}
<div id="testDiv"></div>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415