How to Convert a String to HTML using JavaScript

Updated onbyAlan Morel
How to Convert a String to HTML using JavaScript

JavaScript has many built-in APIs and methods that give you control over the HTML on the page.

One of the most useful ways to control the HTML is by converting a string to HTML.

From there, you can use the HTML to append to the DOM, or use it to replace the current page.

In this post, we'll learn how to convert a string to HTML using JavaScript.

How to convert a String to HTML using JavaScript

To learn how to convert a string to HTML, first let's define the string of HTML:

JAVASCRIPT
const htmlString = ` <main> <h1>Convert a String to HTML</h1> <p>Learn how to convert a string to HTML using JavaScript.</p> </main> `;

Now, we can make use of the built-in DOMParser API to convert the string to HTML.

One of the methods for the DOMParser API is parseFromString(). This method takes two arguments:

  1. The string of HTML to convert
  2. The type of content to parse

We already have the string of HTML, so we just need to pass in the type of content to parse, which is text/html:

JAVASCRIPT
const htmlString = ` <main> <h1>Convert a String to HTML</h1> <p>Learn how to convert a string to HTML using JavaScript.</p> </main> `; const parser = new DOMParser(); const html = parser.parseFromString(htmlString, 'text/html');

From here, we can just take the html and get the body:

JAVASCRIPT
const htmlString = ` <main> <h1>Convert a String to HTML</h1> <p>Learn how to convert a string to HTML using JavaScript.</p> </main> `; const parser = new DOMParser(); const html = parser.parseFromString(htmlString, 'text/html'); const body = html.body; console.log(body);
HTML
<body> <main> <h1>Convert a String to HTML</h1> <p>Learn how to convert a string to HTML using JavaScript.</p> </main> </body>

We can take the above code and turn it into a reusable function:

JAVASCRIPT
const htmlString = ` <main> <h1>Convert a String to HTML</h1> <p>Learn how to convert a string to HTML using JavaScript.</p> </main> `; const convertStringToHTML = htmlString => { const parser = new DOMParser(); const html = parser.parseFromString(htmlString, 'text/html'); return html.body; } const body = convertStringToHTML(htmlString); console.log(body);

If we want, we can take this body and append it to the DOM:

JAVASCRIPT
document.body.appendChild(body);

Conclusion

In this post, we learned how to convert a string to HTML using JavaScript.

Simply use the built-in DOMParser class and call the parseFromString() method to convert your string into HTML.

Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.