The DOMParser interface provides the ability to parse XML or HTML source code from a string into a DOM Document.

You can perform the opposite operation—converting a DOM tree into XML or HTML source—using the XMLSerializer interface.

In the case of an HTML document, you can also replace portions of the DOM with new DOM trees built from HTML by setting the value of the Element.innerHTML and outerHTML properties. These properties can also be read to fetch HTML fragments corresponding to the corresponding DOM subtree.

Note that XMLHttpRequest can parse XML and HTML directly from a URL-addressable resource, returning a Document in its response property.

Note: Be aware that block-level elements like <p> will be automatically closed if another block-level element is nested inside and therefore parsed before the closing </p> tag.



Creates a new DOMParser object.



Parses a string using either the HTML parser or the XML parser, returning an HTMLDocument or XMLDocument.


Parsing XML, SVG, and HTML

This example shows how to parse XML, SVG, and HTML. Note that a MIME type of text/html will invoke the HTML parser, and any of the other MIME types that are accepted by this method will invoke the XML parser.

const parser = new DOMParser();

const xmlString = "<warning>Beware of the tiger</warning>";
const doc1 = parser.parseFromString(xmlString, "application/xml");
// XMLDocument

const svgString = "<circle cx=\"50\" cy=\"50\" r=\"50\"/>";
const doc2 = parser.parseFromString(svgString, "image/svg+xml");
// XMLDocument

const htmlString = "<strong>Beware of the leopard</strong>";
const doc3 = parser.parseFromString(htmlString, "text/html");
// HTMLDocument

// "Beware of the tiger"

// "circle"

// "Beware of the leopard"


HTML Standard (HTML)
# dom-parsing-and-serialization

Browser compatibility

BCD tables only load in the browser

See also