DEV Community

Sh Raj
Sh Raj

Posted on

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

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.

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

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

// convert html string into DOM
const document2 = 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:

  1. text/xml
  2. application/xml
  3. application/xhtml+xml
  4. 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");
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.

Enter fullscreen mode Exit fullscreen mode

See the above code live in JSBin.

That's all πŸ˜ƒ!

Source :- https://melvingeorge.me/blog/convert-html-string-into-real-html-or-dom-javascript

Feel free to share if you found this useful πŸ˜ƒ.

Top comments (0)