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.
textContent gets the content of all elements, including <script> and <style> elements. In contrast, innerText only shows "human-readable" elements. textContent returns every element in the node. In contrast, innerText is aware of styling and won't return the text of "hidden" elements.
textContents is all text contained by an element and all its children that are for formatting purposes only. innerText returns all text contained by an element and all its child elements. innerHtml returns all text, including html tags, that is contained by an element.
The value attribute specifies the value of an <input> element. The value attribute is used differently for different input types: For "button", "reset", and "submit" - it defines the text on the button. For "text", "password", and "hidden" - it defines the initial (default) value of the input field.
In JavaScript, the textContent property allows us to get or set the text content of a node, or an element. Setting the textContent property will remove and replace the child nodes with the new text node. The textContent property returns the content of an element/node and all of its descendents(child nodes).
From 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With