Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot use variables to change css property

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?

like image 222
Caleb Chang Avatar asked Jan 20 '26 03:01

Caleb Chang


1 Answers

In the first example, you are pointing x at the style object that exists for the foo component. When you assign a string to x.backgroundColor, you are effectively assigning a string to document.getElementById("foo").style.backgroundColor since x and style point to the same object in memory.

In the second example, you are simply assigning the style.backgroundColor string to x. You then assign a new string to x.

like image 130
Nick Avatar answered Jan 22 '26 16:01

Nick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!