In the following example, why doesn’t the value property of the input with the ID test update to "second"?
document.getElementById("test").addEventListener("click", () => {
let test = document.getElementById("test").value;
test = "second";
console.log(test); // Logs "second", but input value is not updated.
});
<label>Click on this test input: <input type="text" id="test" value="first"></label>
Because Javascript assigned x as a value and not a reference to the original object.
For example, you could instead:
And the value you set with
setText()will be reflected bygetText(), sincegetText()will also use the reference object’s value, and not a copy of the value.EDIT
As Bryan points out, this would be a copy by reference with a global scope:
http://jsfiddle.net/nLj2A/
The original
testvariable stores a reference to the element, not a value associated with an attribute of the element.