Mozar Mozar - 2 months ago 7
Javascript Question

variable holding style value can't be changed

I am curious about a simple problem. Here is the code:



var square = document.getElementById('square')
var left = square.style.left

function moveNoVariable() {
square.style.left = "100px" // works
}

function moveWithVariable() {
left = "100px" // doesn't work
}

moveNoVariable()

#square {
width: 20px;
height: 20px;
border: 1px solid black;
background-color: red;
position: relative;
}

<div id="square"></div>





I am just wondering why the style won't change if I use "left" even though it is storing the correct value.

Thanks.

Answer

square.style.left is a string. If you put a string into a variable, the variable will store a copy of the given string. If you put an object into a variable, the variable will refer to the original object. So you could do this for example:

var square = document.getElementById('square')
var style = square.style

function moveNoVariable() {
  square.style.left = "100px" // works
}

function moveWithVariable() {
  style.left = "100px" // will work
}
Comments