问题
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.
回答1:
From MDN:
[...]
textContentreturns the concatenation of thetextContentof 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.
回答2:
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.
来源:https://stackoverflow.com/questions/55012375/give-the-difference-between-input-value-and-input-textcontent-why-is-one-used-i