Table of Contents
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:
JAVASCRIPTconst 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:
JAVASCRIPTconst 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:
JAVASCRIPTconst 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:
JAVASCRIPTconst 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:
JAVASCRIPTdocument.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!
Getting Started with Electron
How to Set Up Cron Jobs in Linux
How to deploy a .NET app using Docker
How to deploy a Deno app using Docker
Getting Started with Deno
How to deploy an Express app using Docker
Learn how to use v-model with a custom Vue component
How to Scrape the Web using Node.js and Puppeteer
Build a Real-Time Chat App with Node, Express, and Socket.io
Getting User Location using JavaScript's Geolocation API
Using Axios to Pull Data from a REST API
Getting Started with Moon.js
