DOMParser
{{APIRef("DOM")}}
The DOMParser interface provides the ability to parse {{Glossary("XML")}}XML or {{Glossary("HTML")}}HTML source code from a string into a DOM {{domxref("Document")}}Document.
You can perform the opposite operation—converting a DOM tree into XML or HTML source—using the {{domxref("XMLSerializer")}}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 {{domxref("Element.innerHTML")}}innerHTML and {{domxref("Element.outerHTML", "outerHTML")}}outerHTML properties. These properties can also be read to fetch HTML fragments corresponding to the corresponding DOM subtree.
Note that {{domxref("XMLHttpRequest")}}XMLHttpRequest can parse XML and HTML directly from a URL-addressable resource, returning a Document in its {{domxref("XMLHttpRequest.response", "response")}}response property.
[!NOTE]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.
Constructor
{{domxref("DOMParser.DOMParser","DOMParser()")}}- : Creates a new
DOMParserobject.
- : Creates a new
Instance methods
{{domxref("DOMParser.parseFromString()")}}- : Parses an input
{{domxref("TrustedHTML")}}TrustedHTML instance or string as HTML or XML and returns a{{domxref("Document")}}Document.
- : Parses an input
Examples
The documentation for {{domxref("DOMParser.parseFromString()")}}, this interface's only method, contains examples for parsing XML, SVG, and HTML strings.
Specifications
{{Specifications}}
Browser compatibility
{{Compat}}
See also
- Parsing and serializing XML
{{domxref("XMLHttpRequest")}}XMLHttpRequest{{domxref("XMLSerializer")}}XMLSerializer{{jsxref("JSON.parse()")}}- counterpart for{{jsxref("JSON")}}JSON documents.