开发者

Textarea : elem.val() vs elem.text() [duplicate]

This question already has answers here: val() vs. text() for textarea (2 answers) Closed 5 years ago.

This is very weird. Apparently, I can use both .val() and .text() to manipulate textarea text.

But after I use .val to change the text, I cannot use .text a开发者_C百科nymore. The converse is not true.

This is leading to some funky bugs. The reason is because a plugin i am using might be using .val to manipulate the text.

Can anyone explain how this works? Thanks!


You have to use val(), or (better) the value property of the textarea. text() works initially because the initial value of the textarea is determined by the text node (if any) it contains. You can even initially change the nodeValue or data property of this text node and it will update the textarea's value. However, as soon as either the user has altered the value of the textarea or script has altered the value property of the textarea, the text node is out of the picture and is no longer bound to the textarea's value in any way.


The .val() function gets the "value" attribute of the <textarea> element, while .text() gets the contents of the text nodes (node type 3) in the element. I'd say that if setting .text() works at all, it's not a good idea, as it's essentially fooling around with the basic building blocks of matter. It could cause a bug, or a browser crash, or a devastating explosion.

Use .val().

edit.text() works up to the point at which a user interacts with the <textarea> element, or JavaScript code sets the "value" property. After that point, the DOM content of the element becomes irrelevant. You can still get it, but it won't reflect the actual state of the element.


Sounds strange, but at a lower level, .val() is what I'm expecting to work since .value is the way to access the content of form-elements. Why .text() is working in some cases beats me


Has to with the type of Node .text() retrieves...

.Text() gets the innerText (not HTML) of all the matched elements and .val() retrieves values from input elements...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜