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:
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:
- The string of HTML to convert
- 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
:
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:
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);
<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:
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:
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!
If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on X! You can also join the conversation over at our official Discord!
Leave us a message!