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");
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>";
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();
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");
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 π!
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)