Give the difference between input.value and input.textContent. Why is one used instead of the other?

天涯浪子 提交于 2020-08-19 00:46:48

问题


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:

[...] textContent returns the concatenation of the textContent 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.




回答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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!