DOMParser
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.
Browser support
| Feature | Desktop | Mobile | ||||
|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Safari | Chrome Android | Safari iOS | |
| 1 | 12 | 1 | 1.3 | 18 | 1 | |
| The DOMParser() constructor creates a new DOMParser object. This object can be used to parse the text of a document using the parseFromString() method. | 1 | 12 | 1 | 1.3 | 18 | 1 |
| The parseFromString() method of the DOMParser interface parses an input containing either HTML or XML, returning a Document with the type given in the Document/contentType property. | 1 | 12 | 1 | 1.3 | 18 | 1 |
parseFromString (html) HTML (`text/html`) support | 31 | 12 | 12 | 9.1 | 31 | 9.3 |
parseFromString (xml) XML (`application/xml`) support | 1 | 12 | 1 | 1.3 | 18 | 1 |
Use cases
-
Using DOMParser
The DOMParser interface provides the ability to parse XML or HTML source code from a string into a DOM Document.
Cautions
- May not be supported in older browsers.
Implementation notes
- Some APIs require a secure context (HTTPS) or user activation. Check the requirements before use.