1

HTML <textarea/> element simultaneously contains 2 "value" fields; and only one of which is visible on viewing the html source of the element. (illustrated in the example below).

Can someone explain why this is so and where does the "Type2" value get stored here?

Theory: What is the difference between properties and attributes in HTML?

var dummy = document.createElement("textarea");
document.body.appendChild(dummy);
dummy.setAttribute('value', "Type1");
dummy.value = "Type2";

console.log("attributeValue is " + dummy.getAttribute('value'));
console.log(".value is " + dummy.value);
Henderz
  • 31
  • 5

1 Answers1

2

Your setAttribute() call applies a value attribute to the textarea element in the DOM. This is technically incorrect as textarea elements do not have a value attribute.

You then set the value property of the element. This is the correct usage, and is what sets the visible text within the element.

The result of this logic is this HTML:

<textarea value="Type1">Type2</textarea>

When you use getAttribute() you read the (non-standard) value attribute from the element which returns Type1.

When you read the value property you are (correctly) reading the value contained within the user editable content of the field, which returns Type2.

In short, the confusion you have is because you're using an attribute named value and property named value, and they are not the same thing when applied to a textarea.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339