Render HTML inside a textarea

Question

I was wondering if it’s possible to render HTML inside a textarea? So if I place HTML content in it, it would be instantly rendered and displayed.

Answer ( 1 )

    0
    2023-01-25T17:30:35+00:00

    You can’t really render HTML in a textarea. What you can do is to add a separate div with the contenteditable attribute set to true. And display the textarea content into that div.

    You would want to do something like this:

    <form>
    <textarea id="text" cols="30" rows="10">
    Hello this is <strong>just</strong> a <em>text</em>.
    </textarea>
    </form>
    
    <div id="preview" contenteditable="true"></div>

    and then inject the content of the textarea into the div with javascript

    const textArea = document.getElementById('text');
    const preview = document.getElementById('preview');
    
    preview.innerHTML = textArea.textContent;

    Note that this is not instant. For that you would probably need some more Javascript magic.

Leave an answer