I have a text box which automatically changes the value entered by the user to uppercase, the code works just the way I want it to:
function myFunction() {
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
However, if I re-write it as follows, it does not change the text box value to uppercase :
function myFunction() {
var x = document.getElementById("fname").value; <--- notice I added value here
x = x.toUpperCase();
}
My impression was that both excerpts would serve the same purpose, so why is it that the second one does not work the way I intend it to?
In first snippet, x
is a DOM Element whose value
attribute you change by assigning
x.value = x.value.toUpperCase();
In the second snippet, x
is just a plain String
which holds no reference to the DOM element. It's same as doing "someString" = "someOtherString"
and obviously, it won't be reflected in the DOM, as there is no reference to the DOM element anywhere.
Summary:
setter
, so the value
gets uptated. getter
and changing the returned value of it, which doens't reflect in the DOM element.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.