Categories
JavaScript Answers

How to Render HTML Inside a Text Area with JavaScript?

Spread the love

Sometimes, we want to render HTML inside a text area.

In this article, we’ll look at how to render HTML content inside a text area.

Render Content in a contenteditable Div

An HTML text area can’t render HTML.

However, we can make a div’s content editable with the contenteditable attribute.

Therefore. we can use an editable div as we do with a text area but with HTML content.

For instance, we can write the following HTML:

<div class="editable" contenteditable="true"></div>
<button class="bold">toggle red</button>
<button class="italic">toggle italic</button>

Then we can style it with the following CSS:

.editable {
  width: 300px;
  height: 200px;
  border: 1px solid #ccc;
  padding: 5px;
  resize: both;
  overflow: auto;
}

And then we can get the buttons and change the text when we click on them:

const bold = document.querySelector('.bold')
const italic = document.querySelector('.italic')
const editable = document.querySelector('.editable')

const toggleRed = () => {
  const text = editable.innerHTML;
  editable.innerHTML = `<p style="color:red">${text}</p>`;
}

const toggleItalic = () => {
  const text = editable.innerHTML;
  editable.innerHTML = `<i>${text}</i>`;
}

bold.addEventListener('click', toggleRed);
italic.addEventListener('click', toggleItalic);

We make the div editable with the contenteditable attribute set to true .

We select all the elements we added with document.querySelector .

Then we have the toggleRed function that gets the existing innerHTML from the editable div.

Then we add a p element with color style set to red.

Likewise, we have the toggleItalic function to get the innerHTML from the editable div.

Then we wrap the i tag around the text.

The CSS just sets the width, border, padding, and overflow styles for the editable div.

Now when we click on toggle red and toggle italic, we see the corresponding styles applied to the text we typed into it.

Conclusion

We can render HTML in an editable div instead of a text area if we want to add a box where we can edit rich text.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.