I am trying to change the background-color of an element by clicking on a button. In 2 implementations of javascript, I am storing slightly different values in the same variable, and using the variables to change the background-color. I expect both implementations to work, but only one works. Here are the details.
In HTML, I have a <div id="foo">Lorem</div> element and a <button id="button">Click</button> element.
I have 2 different codes for JavaScript. The first one is:
var button = document.getElementById("button");
var x = document.getElementById("foo").style;
button.addEventListener("click",function(){
x.backgroundColor="red";
});
The second one is:
var button = document.getElementById("button");
var x = document.getElementById("foo").style.backgroundColor;
button.addEventListener("click",function(){
x="red";
});
The first one works, but the second one does not. The only difference between the two code snippets is in the first one, the variable x did not include backgroundColor and the background color of x was changed using x.backgroundColor="red";. In the second one, the variable x did include backgroundColor and the color was changed(tried to change) using x="red";.
Why does the first way work, but the second way does not?