DEV Community

Cover image for How to convert an HTML string into real HTML or DOM using JavaScript?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

How to convert an HTML string into real HTML or DOM using JavaScript?

Originally posted here!

To convert an HTML string into real HTML or DOM, you can use the DOMParser Web API using JavaScript. The DOMParser helps us to parse HTML or XML string into real Document or DOM nodes.

TL;DR

// html string
const htmlStr = "<h1>Hello World!</h1>";

// make a new parser
const parser = new DOMParser();

// convert html string into DOM
const document = parser.parseFromString(htmlStr, "text/html");
Enter fullscreen mode Exit fullscreen mode

For example, let's say you have a HTML string of h1 tag with the text of Hello World! like this,

// html string
const htmlStr = "<h1>Hello World!</h1>";
Enter fullscreen mode Exit fullscreen mode

Now, to convert this string into a real HTML tag we can use the DOMParser web API.

So first, we have to make a parser using the new keyword like this,

// html string
const htmlStr = "<h1>Hello World!</h1>";

// make a new parser
const parser = new DOMParser();
Enter fullscreen mode Exit fullscreen mode

After that, we can use the parseFromString() method in the parser object and pass:

  • the raw HTML string as the first argument
  • and the mime type or the type of the document contained in the string as the second argument. In our case, the mime-type value is text/html.

There are other mime types we can use such as:

  • text/xml
  • application/xml
  • application/xhtml+xml
  • image/svg+xml

So it will look like this,

// html string
const htmlStr = "<h1>Hello World!</h1>";

// make a new parser
const parser = new DOMParser();

// convert html string into DOM
const document = parser.parseFromString(htmlStr, "text/html");
Enter fullscreen mode Exit fullscreen mode

Now the HTML string is converted to an HTML DOM node. You can now use the usual methods and properties available on a DOM node such as appendChild(), classList, etc.

See the above code live in JSBin.

That's all 😃!

Feel free to share if you found this useful 😃.


Top comments (2)

Collapse
 
klo2k profile image
klo2k

Thanks for this 👍

Collapse
 
xsxsatellite profile image
XieShixin

Thank you sir, I am searching for this and find your answer.