'Should I use .innerText or .value in JavaScript?
There's a problem I've encountered but can't find explanation so far. The code is as follows:
let textbox = document.getElementById("textbox");
let result = document.getElementById("result");
function convertToCm() {
value = textbox.value;
result.innerText = +value * 2.54;
document.body.appendChild(result);
}
<input id="textbox" type="text">
<button onclick="convertToCm()">Convert to cm</button>
<div id="result">result</div>
In the second line of the function, I tried to use textbox.innerText
instead, however this gives me output of 0 of whichever number I put in the textbox. In the third line, I also tried to use result.value
instead, but it would then output the same number I put in the textbox. I'm really confused.
I've tried looking on a search engine but haven't found an explanation so far. What can I try next?
Solution 1:[1]
To get or set value from input field we need to use .value as you write textbox.value
which is correct.
<input id="textbox" type="text">
To get or set value from common elements (it could be any element/tag) we use .innerText as you write result.innerText
which is correct.
<div id="result">result</div>
Also you don't need document.body.appendChild(result);
line in your code.
Solution 2:[2]
Your textbox
refers to an HTMLInputElement (or <input>
), which is a void element. As such, its .innerText
is always an empty string.
Converting an empty string to a number will evaluate to zero.
Instead, use .value
to read or write to a form control's value (form controls are for example <input>
, <select>
, <textarea>
).
To read or write a non-void element's text, use .innerText
(or preferably .textContent
, as it doesn't cause a reflow). Your variable result
references an HTMLDivElement—a non-void element.
In the second line you update result.innerText
. This will be reflected in the DOM immediately.
Because result
already exists in the DOM, and is updated as you wanted, it is actually unnecessary to reappend it.
Feedback:
I recommend to keep functionality purely in your <script>
(or JS file) for maintainability. Using the onevent HTML attributes is (usually) deprecated. Instead, use addEventListener()
:
- Allows multiple event listeners to be added.
- Allows setting of
options
for the listener. - Easier finding of dead code.
- The event object is always passed as the first argument, instead of having to manually pass it or use the deprecated
window.event
property. - Doesn't clutter the HTML.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Ketan Kale |
Solution 2 |