parseFromString() method
By FoxLearn 2/8/2025 2:33:01 AM 71
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); }
- How to format number with commas and decimal in Javascript
- How to Pass string parameter in an onclick function
- What does 'use strict;' means in Javascript
- How to detect if caps lock is pressed in Javascript
- How to create a Custom Event in Javascript
- How to Check if an Object Has a Property Properly in JavaScript
- How to convert an Uint8Array to string in Javascript
- How to copy text to clipboard in Javascript
Categories
Popular Posts
Freedash bootstrap lite
11/13/2024
Admin BSB Free Bootstrap Admin Dashboard
11/14/2024
K-WD Tailwind CSS Admin Dashboard Template
11/17/2024
Spica Admin Dashboard Template
11/18/2024