JavaScript - How to Change the Content of a <Textarea> ?
Here are the various methods to change the content of a textarea using JavaScript.
1. Using value Property
The value property is the most common method to change or retrieve the content of a <textarea>.
<textarea id="myTextarea">Initial content</textarea>
<button onclick="changeContent()">Change Content</button>
<script>
function changeContent() {
const textarea = document.getElementById("myTextarea");
textarea.value = "New content using value property!";
}
</script>
Output

2. Using innerHTML Property
While innerHTML is not typically used for <textarea>, it can modify its content when treated as a standard HTML element.
<textarea id="myTextarea">Initial content</textarea>
<button onclick="changeContent()">Change Content</button>
<script>
function changeContent() {
const textarea = document.getElementById("myTextarea");
textarea.innerHTML = "New content using innerHTML!";
}
</script>
Output

3. Using innerText Property
Similar to innerHTML, this property modify the visible text of the <textarea>.
<textarea id="myText">Initial content</textarea>
<button onclick="changeText()">Change Content</button>
<script>
function changeText() {
const textarea = document.getElementById("myText");
textarea.innerText = "New content using innerText!";
}
</script>
Output

4. Using Event Listeners for Dynamic Updates
You can use event listeners to change the content interactively.
<textarea id="myText">Initial content</textarea>
<button id="updateButton">Change Content</button>
<script>
document.getElementById("updateButton").addEventListener("click", () => {
const textarea = document.getElementById("myText");
textarea.value = "Content updated using event listeners!";
});
</script>
Output

Which approach to choose?
- value Property: Most common and versatile.
- innerHTML/innerText: Rarely used for <textarea>; more suited for other elements.
- Event Listeners: Best for dynamic and interactive updates.