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 TypeScript
Managing PHP Dependencies with Composer
How to Serve Static Files with Nginx and Docker
How to deploy a PHP app using Docker
How to deploy a Deno app using Docker
How to deploy a MySQL Server using Docker
How to deploy a Node app using Docker
How to Scrape the Web using Node.js and Puppeteer
Getting Started with Handlebars.js
Learn how to build a Slack Bot using Node.js
Setting Up Stylus CSS Preprocessor
How To Create a Modal Popup Box with CSS and JavaScript
