What is the purpose of textContent in an input element?

时光总嘲笑我的痴心妄想 提交于 2021-01-27 12:15:13

问题


Provided an input element in a DOM, it does have a textContent property along with value. It is well known that the value of the input is what shown in the text box, and this element cannot have any children, that is <input>something</input> still gives an empty input followed by a sibling text node, whereas closing tag is completely ignored. But when we set a value to the textContent of this input, it is somehow survives the round-trip:

input.textContent = 'something'
console.log(input.textContent)  // this works

Also, after setting the property, the input appear as having child elements in the inspector:

Maybe it's just me, but I fail to see any logical consistency here. Wouldn't it be nice to have a Type Error on setting text content to the input?

Is there any reasoning behind present behaviour?


回答1:


The DOM is not HTML, but an API for tree structures that comply with the XML information set Translating <input>something</input> into an input element followed by a text node is the behaviour of the HTML parser, not the behaviour of the DOM.

In fact, if you use XHTML, served as application/xhtml+xml, <input>something</input> will become an input element with a text node child, the same as using .textContent. So it's entirely normal that .textContent works the way it does.



来源:https://stackoverflow.com/questions/37143171/what-is-the-purpose-of-textcontent-in-an-input-element

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