How to Display HTML content in Textarea Using Javascript

Advertisement

In this tutorial, we’ll walk you through the steps to display HTML content inside a textarea using JavaScript?.

Getting Started

Before we dive into the code, make sure you have a basic understanding of HTML, CSS, and JavaScript. You’ll need these skills to follow along.

HTML Structure

Let’s begin by setting up our HTML structure. Create an HTML file and add the following code:

<!DOCTYPE html>
<html>
<head>
    <title>Display HTML in Textarea</title>
</head>
<body>
    <textarea id="htmlTextarea"></textarea>
</body>
</html>

In this example, we’ve created a simple HTML page with a textarea element that has the ID “htmlTextarea.” We’ll use this textarea to display HTML content.

Writing JavaScript

Now, let’s write the JavaScript code to display HTML content in the textarea.

// Get the textarea element by its ID
const textarea = document.getElementById('htmlTextarea');

// HTML content to display
const htmlContent = '<h1>Hello, World!</h1><p>This is some HTML content.</p>';

// Set the textarea's value to the HTML content
textarea.value = htmlContent;

In this JavaScript code:

  • We use document.getElementById to select the textarea element with the ID “htmlTextarea.”
  • We define an htmlContent variable that contains the HTML we want to display.
  • Finally, we set the value property of the textarea to our HTML content.

Testing Your Code

Save your HTML file and open it in a web browser. You should see the HTML content displayed within the textarea.

Dynamically Updating the Content

Now, let’s take it a step further and update the HTML content dynamically when the user interacts with the page. We’ll use a button to trigger the update.

HTML Button

Add a button to your HTML file:

<button id="updateButton">Update Content</button>

JavaScript for Dynamic Update

Here’s the JavaScript code to update the textarea content when the button is clicked:

// Get the update button element by its ID
const updateButton = document.getElementById('updateButton');

// Add a click event listener to the button
updateButton.addEventListener('click', () => {
    // New HTML content
    const newHtmlContent = '<p>New content added!</p>';
    
    // Append the new content to the existing content
    textarea.value += newHtmlContent;
});

Now, when you click the “Update Content” button, the new HTML content will be appended to the existing content in the textarea.

author's bio photo

Hi there! I am Avic Ndugu.

I have published 100+ blog posts on HTML, CSS, Javascript, React and other related topics. When I am not writing, I enjoy reading, hiking and listening to podcasts.