Sometimes, we want to change the content of a text area element with JavaScript.
In this article, we’ll look at how to change the content of an HTML text area element with JavaScript.
Change the value Property of the Text Area Element
We can change the content of a text area by setting the value of the value
property of a text area element.
For instance, if we have the following HTML:
<textarea></textarea>
Then we can set the content of the text area by writing:
document.querySelector('textarea').value = 'hello world';
We select the text area with the document.querySelector
method.
Then we assign a value to the value
property of the text area.
Therefore, now we should see a text area with ‘hello world’ as the content.
Change the innerHTML Property of the Text Area Element
Another property of the text area element that we can change to add content to the text area element is the innerHTML
property.
For instance, if we have the following HTML:
<textarea></textarea>
Then we can set the content of the text area by writing:
document.querySelector('textarea').innerHTML = 'hello world';
We select the text area with the document.querySelector
method.
Then we assign a value to the innerHTML
property of the text area.
Therefore, now we should see a text area with ‘hello world’ as the content also.
Select a Text Area in a Form from the document.forms Property
If our text area is in a form element, then we can get the text area by the name
property of the text area in the form.
For example, if we have the following form:
<form name="form">
<textarea name="textarea" rows="10" cols="60"></textarea>
</form>
Then we can assign the value
property of the text area in the form by writing:
document.forms.form.textarea.value = 'hello world';
form
and textarea
are values of the name
attribute for the form and textarea
elements respectively.
And so we should see ‘hello world’ in the text area.
Conclusion
We can get the text area with querySelector
or document.forms
if it’s in a form.
Then we can assign a value to the innerHTML
or value
property to change its content.