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. 

Explore More

How to Center a Popup Window on Screen

JavaScript window.open() method is used to open a popup window. This popup window will be placed in the center of the screen. This example creates the pop-up window without placing it into

How to hide URL in the popup window opened using window.open

If you are using below code to open a popup window in your web page, then address must be appearing in you pop up window and f you want to

window.showModalDialog is deprecated in Edge and Chrome

If you have a website being compatible with Edge/Chrome and in past it was only compatible with IE 11 and if you are using window.showModalDailog in your JavaScript code, then