How to Parse a String to HTML Using JavaScript?

Estimated read time 1 min read

You can parse a string to HTML using JavaScript using innerHTML property or createElement() method.

Here is an example of using innerHTML:

let htmlString = "<p>This is a paragraph.</p>";
let targetDiv = document.getElementById("targetDiv");
targetDiv.innerHTML = htmlString;

And here is an example of using createElement():

let htmlString = "<p>This is a paragraph.</p>";
let targetDiv = document.getElementById("targetDiv");
let parser = new DOMParser();
let parsedHTML = parser.parseFromString(htmlString, "text/html");
let pElement = parsedHTML.body.firstChild;
targetDiv.appendChild(pElement);

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply