DOMParser: parseFromString() method

The parseFromString() method of the DOMParser interface used to parses a string containing either HTML or XML and then returning an HTMLDocument or XMLDocument respectively.

parseFromString(InputString, mimeType)

Below is the detail of input parameters

String: The string to be parsed. It must contain either HTML, XHTML, xml or svg document.

  • text/html
  • text/xml
  • application/xml
  • application/xhtml+xml
  • image/svg+xml

Return value:

Return value will be HTMLDocument or an XMLDocument, depending on the mimeType argument.

Examples:

const parser = new DOMParser();

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

const svgStringData = '<circle cx="40" cy="40" r="40"/>';
const doc2 = parser.parseFromString(svgStringData, "image/svg+xml");
// XMLDocument

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


// ****** output will display using below console.log() ******

console.log(doc1.documentElement.textContent);
// "Beware of the XYZ"

console.log(doc2.firstChild.tagName);
// "circle"

console.log(doc3.body.firstChild.textContent);
// "Beware of the ABC"

Error handling can be done as given below:

const parser = new DOMParser();

const xmlString = "<warning>Hay! you are missing closing tag";
const doc = parser.parseFromString(xmlString, "application/xml");
const errorNode = doc.querySelector("parsererror");
if (errorNode) {
  // parsing  has failed.
} else {
  // parsing  is succeeded.
}

// you can also wrap this code in try/catch block. 

Leave a Reply

Your email address will not be published. Required fields are marked *