Home > Blockchain >  Why cannot I set the value attribute of texarea by setAttribute?
Why cannot I set the value attribute of texarea by setAttribute?

Time:02-12

<textarea value="hello" id="id1"></textarea>

The above textarea does not show "hello" in it.

document.getElementById('id1').setAttribute("value", "hello");
<textarea value="hello" id="id1"></textarea>

This textarea does not show "hello", either. But the following one does show "hello" in it, why?

document.getElementById('id1').value = "hello";
<textarea value="hello" id="id1"></textarea>

The setAttribute works perfectly for <input> element:

document.getElementById('id1').setAttribute("value", "hello");
<input value="" id="id1" />

CodePudding user response:

A textarea does not have a value attribute to set using setAttribute - it has a value property you set directly using the element.value

Compare

<textarea>value</textarea>

to

<input value="value"/>

where value is an attribute of the input element

CodePudding user response:

In DOM, input and textarea elements have a defaultValue property. This controls what is displayed in the element if the user doesn't type anything or if the form is reset.

For an input element the defaultValue property maps onto the value attribute.

For a textarea element the defaultValue property maps onto the text content of the element. textarea elements do not have a value attribute.


Both kinds of element have a value property which represents the current value.

That this has the same name as the input elements value attribute is unfortunate and a source of a fair bit of confusion.

  • Related