html-dom-parser is a versatile JavaScript library designed to convert HTML strings into a structured JavaScript object representation of the Document Object Model (DOM) tree. It operates effectively in both Node.js environments (leveraging `htmlparser2` and `domhandler` internally for performance) and client-side browser contexts (mimicking server parsing behavior using the native DOM API). Currently at version 7.0.1, the library maintains a relatively active release cadence, with multiple updates in recent months addressing bug fixes and dependency bumps. Its key differentiator lies in providing a consistent, serializable DOM-like output (Plain Old JavaScript Objects) across different JavaScript environments, making it suitable for server-side HTML manipulation, client-side virtual DOM implementations, or data extraction where direct DOM access might be unavailable or inefficient.
npm install html-dom-parserVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to parse a basic HTML string, including how to apply server-side parsing options for more complex scenarios, and access properties of the resulting DOM nodes.
Review your parsing logic and expected DOM structures, particularly for complex or malformed HTML inputs. Consult the `htmlparser2` v12 changelog for specific behavioral changes.
If you relied on `formatAttributes` or `CARRIAGE_RETURN`, you will need to find alternative implementations or manually handle these aspects. Review the changelogs for `htmlparser2` and `domhandler` for changes in DOM node structure or parsing behavior that might affect your application.
Always use `import parse from 'html-dom-parser';` for ESM and `const parse = require('html-dom-parser').default;` for CommonJS to ensure correct module resolution. Upgrade to the latest stable version (7.x.x) to benefit from build and type fixes.Ensure you are running version 5.1.8 or higher, or the latest 7.x.x series, to protect against this and other potential security vulnerabilities.
For CommonJS, use `const parse = require('html-dom-parser').default;` to correctly access the default exported parser function.Ensure your project is configured for ESM (`"type": "module"` in `package.json` or `.mjs` extension). If issues persist, verify that your build tools (e.g., Rollup, Webpack) are correctly bundling ESM-only dependencies for CJS output if required, and upgrade to the latest `html-dom-parser` version (>=5.1.7) which includes fixes for ESM bundling.
Use type guards to narrow the type of the node before accessing specific properties, e.g., `if ('name' in node && node.type === 'tag') { console.log(node.name); }` or `if (node instanceof Element) { console.log(node.name); }` (though `Element` class might not be directly exported or identical to `domhandler`'s `Element` type).