Why is it that input.value
is used instead of input.textContent
. What is the difference between both?
For example, if I want to retrieve content from an input box
<input type="number">
I have to use this code
var input = document.querySelector("input");
input.value
instead of this one
input.textContent
Just want to get a clearer understanding of each.
Why is it that input.value
is used instead of input.textContent
. What is the difference between both?
For example, if I want to retrieve content from an input box
<input type="number">
I have to use this code
var input = document.querySelector("input");
input.value
instead of this one
input.textContent
Just want to get a clearer understanding of each.
Share Improve this question edited Sep 10, 2021 at 12:39 Paolo 21.1k21 gold badges76 silver badges121 bronze badges asked Mar 5, 2019 at 22:08 JoanJoan 4221 gold badge6 silver badges16 bronze badges 6 | Show 1 more comment2 Answers
Reset to default 11From MDN:
[...]
textContent
returns the concatenation of thetextContent
of every child node, excluding comments and processing instructions. This is an empty string if the node has no children.
Essentially, textContent
gives you a textual representation of what a node contains. Think of it as being everything between the opening and closing tags, e.g.
console.log(document.querySelector('span').textContent);
<span> this text </span> but not this one
<input>
elements however cannot have children (content model: nothing). The value that is associated with them can only be accessed via the value
property.
Only input elements have a "value". It represent the input data supplied by the user or provided initially by the code. Whereas textContent property sets or returns the text content of the specified node, and all its descendants.
textContent returns the concatenation of the textContent of every child node, excluding comments and processing instructions and if if the node has no children then textContent will be empty string.
input.value
is for form elements to get the value of the form element.input.textContent
is for other elements to get the content of the element. – Get Off My Lawn Commented Mar 5, 2019 at 22:10textContent
essentially gets all Text children of the node. Every Element node has this property. Think of it as litterally getting the text between the the opening and closing tags (i.e.<span>this text</span>
). But it only works for elements that have children. An input element node doesn't have children. – Felix Kling Commented Mar 5, 2019 at 22:47<input type="text" value="something">
. There's no text between the start and end tags (since there's no end tag [technically there's no start tag either]), so notextContent
, but there is avalue
attribute. – Heretic Monkey Commented Mar 5, 2019 at 22:53