parseFromString() method

By FoxLearn 2/8/2025 2:33:01 AM   20
The parseFromString() method of the DOMParser interface is used to parse a string that contains either HTML or XML content and return either an HTMLDocument or XMLDocument, depending on the mimeType passed.

parseFromString(InputString, mimeType)

Parameters:

  • InputString: A string to be parsed. It must contain either HTML, XHTML, XML, or SVG document content.
  • mimeType: The MIME type describing the type of the content being parsed. Some valid MIME types include:
    • text/html
    • text/xml
    • application/xml
    • application/xhtml+xml
    • image/svg+xml

Return Value:

The return value is either an HTMLDocument or an XMLDocument, depending on the mimeType provided.

For example:

const parser = new DOMParser();

// Example 1: Parsing XML data
const xmlData = "<book><title>Introduction to JavaScript</title></book>";
const xmlDoc = parser.parseFromString(xmlData, "application/xml");
// XMLDocument

// Example 2: Parsing SVG data
const svgData = '<rect width="100" height="100" style="fill:blue;" />';
const svgDoc = parser.parseFromString(svgData, "image/svg+xml");
// XMLDocument

// Example 3: Parsing HTML data
const htmlData = "<p>Learning JavaScript is fun!</p>";
const htmlDoc = parser.parseFromString(htmlData, "text/html");
// HTMLDocument

// Output display using console.log()
console.log(xmlDoc.documentElement.textContent);
// "Introduction to JavaScript"

console.log(svgDoc.firstChild.tagName);
// "rect"

console.log(htmlDoc.body.firstChild.textContent);
// "Learning JavaScript is fun!"

Error Handling:

If there’s a syntax error in the parsed string, you can handle it as follows:

const parser = new DOMParser();
const invalidXml = "<book><title>Missing closing tag";
const doc = parser.parseFromString(invalidXml, "application/xml");

const errorNode = doc.querySelector("parsererror");
if (errorNode) {
  console.log("Parsing failed!");
} else {
  console.log("Parsing succeeded!");
}

// Or use try/catch for error handling:
try {
  const doc = parser.parseFromString(invalidXml, "application/xml");
  // Check if parsing is successful
} catch (e) {
  console.log("Error during parsing:", e);
}