htmlparser2: a forgiving HTML and XML parser for Node.js
The fast & forgiving HTML and XML parser
At a glance
- What is it?
- htmlparser2 is a callback-driven parser that trades strict spec compliance for speed and tolerance of malformed markup. Its ecosystem includes domhandler, css-select and cheerio, and it installs with a single npm command.
- Who is it for?
- Adopt htmlparser2 when you need to consume HTML or XML quickly and can tolerate non-spec output, especially if you already build on domhandler, domutils or css-select. Do not adopt it when you need strict HTML5 tree construction; the README points at parse5 for that.
- Can I use it commercially?
- Yes. MIT is a permissive licence: you can use, modify and sell software built on it, as long as you keep its copyright and licence notices.
- Is it still maintained?
- Yes. The repository last received commits 2 days ago.
- What is it written in?
- Mainly TypeScript, according to GitHub's language statistics.
Answers come from the project's GitHub data, last synced on November 22, 2026, and from our analysis. They are not legal advice.
Star history
- fb55/htmlparser24,794 ★ · +4
| Repository | 2026-09-23 | 2026-11-22 |
|---|---|---|
| fb55/htmlparser2 | 4.8k | 4.8k |
4 Stars in the last 60 days, measured from the daily GitHub snapshot. Compare with other projects
Editorial analysis
The problem htmlparser2 solves: markup that is not well formed
Real pages arrive broken. Tags stay unclosed, attributes lose their quotes, and script bodies contain characters that look like markup. A parser that rejects any of this is useless for scraping, feed reading or build tooling, because the input is not under your control. htmlparser2 is built around that reality: the README calls it "the fast & forgiving HTML/XML parser" and states plainly that it "takes some shortcuts" to get there.
The audience is narrow and identifiable. It is for Node.js engineers who need to walk a document, not render it: people writing scrapers, RSS and Atom readers (the package keywords list rss, feed and atom), template linters, or the parsing stage of a larger pipeline. It is also infrastructure for other libraries. The README's ecosystem table lists domhandler, domutils, css-select, cheerio and dom-serializer, all of which sit on top of this parser rather than replacing it.
How the callback interface works and where the DOM comes from
The core API is a Parser object constructed with a handler. Every callback is optional; you implement the subset you care about. The README documents events including onopentag(name, attribs, isImplied), onopentagname(name), onattribute(name, value, quote), onclosetag(name, isImplied), ontext(data), oncomment(data), oncdatastart, oncdataend, onprocessinginstruction(name, data), oncommentend, onparserinit, onreset, onend and onerror.
Two details in that table matter more than the rest. First, ontext "may fire multiple times for a single text node", so any consumer that needs whole text must accumulate fragments and stitch them together. The README's own example output shows this, with the note "with multiple text events combined".
The isImplied flag on onopentag and onclosetag is HTML-mode only and tells you the parser inserted or closed a tag on your behalf. The onattribute callback exposes the quote character, distinguishing double quotes, single quotes, unquoted values, and attributes with no value at all such as disabled. If you do not need the aggregated attributes object, the README suggests using onopentagname and onattribute instead, which avoids allocating it.
For a tree, you do not use this package alone. domhandler is the handler that turns the event stream into a DOM, and domutils provides utilities over that DOM. The README points readers at a "Getting a DOM" section for the more ergonomic path. The trade-off is explicit: the callback interface is there for minimal allocation, and the DOM layer is there for convenience.
Installing htmlparser2 and parsing your first document
The package is published on npm and the README gives one installation line. Run it in your project directory:
npm install htmlparser2package.json declares "type": "module", so the package is ESM. The exports map exposes three entry points: the root, ./WritableStream and ./WebWritableStream. Import the root for the Parser class.
The README's usage example is the shortest path to a working parse. It writes a string containing a script tag and then calls end():
import * as htmlparser2 from "htmlparser2";
const parser = new htmlparser2.Parser({
onopentag(name, attributes) {
if (name === "script" && attributes.type === "text/javascript") {
console.log("JS! Hooray!");
}
},
ontext(text) {
console.log("-->", text);
},
onclosetag(tagname) {
if (tagname === "script") {
console.log("That's it?!");
}
},
});
parser.write("Xyz <script type='text/javascript'>const foo = '<<bar>>';</script>");
parser.end();What you should see is the sequence the README prints: the text Xyz, then the JS! Hooray! line from the opening tag handler, then the script body as text, then the closing-tag line. The point of the example is the string inside the script: '<<bar>>' contains characters that would confuse a naive tokenizer, and the parser keeps them as text.
Two practical notes. Parser instances are reusable: onparserinit fires when the parser is initialized or reset, and onreset fires when parser.reset() is called, so you can clear state rather than constructing a new parser for every document. And because the parser is written for streaming, write() can be called repeatedly with chunks; end() signals completion and triggers onend. The README links a live demo on AST Explorer if you want to inspect the event stream before writing handlers.
What htmlparser2 does not do: strict tree construction
The README's own warning is the most important sentence in it: htmlparser2 "takes some shortcuts" and readers who "need strict HTML spec compliance" should look at parse5 instead. That is not marketing hedging, it is a boundary. If your application must reproduce exactly how a browser builds a tree from malformed input, this parser is the wrong tool, because it does not implement the full HTML5 tree-construction algorithm.
The consequences show up in edge cases. Text may arrive split across several ontext calls, which means naive substring matching against a text node can miss a match that spans fragments. Attributes without values are reported with an undefined quote, and unquoted values with null, so handlers that assume every attribute is a quoted string will need to handle both.
The events table lists an onerror callback that fires on error.
htmlparser2 vs parse5: two different jobs
The comparison is not close, because the two projects optimize for opposite things. parse5 implements HTML parsing to the specification, including the error-recovery rules that browsers follow, so its output tree matches what a browser would build. htmlparser2 skips those rules in exchange for speed and tolerance, as the README states directly.
That difference changes what you can do downstream. With parse5 you can reason about document structure the way a rendering engine does: implied elements, foster parenting, the exact handling of misnested formatting tags. With htmlparser2 you get a stream of events that is cheap to consume and forgiving of input, but you cannot assume the tree matches a browser's. For a scraper that wants the text and links out of a page, that distinction rarely matters. For a tool that must decide how a browser would interpret a document, it matters completely.
The practical rule: if you are already using cheerio, css-select or domutils, you are on the htmlparser2 side of the line and switching parsers means changing more than one dependency. If you need spec-accurate tree construction, start with parse5 and accept the cost.
Licence, maintenance and the cost of upgrading
The repository is MIT licensed, and package.json confirms "license": "MIT" with the author listed as Felix Boehm. MIT is permissive: it allows use in closed-source products provided the copyright notice and permission notice are retained. That is a general observation about the licence text, not legal advice; read the LICENSE file in the repository for the exact terms.
The repository is not archived and the last push was on 2026-11-02, so the project is being worked on. The release history shows a major-version cadence worth planning around: v10.1.0 on 2026-01-21, v11.0.0 on 2026-03-19, and v12.0.0 on 2026-03-20. Two majors landed one day apart, with v11.0.0 followed almost immediately by v12.0.0. That pattern suggests v11 was short-lived, and it is a reason to pin your dependency rather than float on a caret range if you upgrade slowly.
Upgrade cost is concentrated in the interface you consume. The package is ESM ("type": "module") with an exports map for the root, ./WritableStream and ./WebWritableStream, so CommonJS consumers need to account for that. The published files include dist and src, excluding specs, fixtures and snapshots, so you get TypeScript sources alongside the compiled output. The repository also carries biome.json and eslint.config.mjs, and the lint script runs eslint, tsc --noEmit and biome, which tells you the maintainers gate on type checking as well as formatting.
Editorial conclusion
Adopt htmlparser2 when you need to consume HTML or XML quickly and can tolerate non-spec output, especially if you already build on domhandler, domutils or css-select. Do not adopt it when you need strict HTML5 tree construction; the README points at parse5 for that. Before committing, verify that your input is not depending on error-recovery rules the parser does not implement, and check the Parser options table in the README for the XML mode and decoding settings your documents require.
Frequently asked questions
What does an HTML parser do?
It reads markup and turns it into a structure a program can act on. In htmlparser2 that structure is a stream of callbacks such as onopentag, ontext and onclosetag, or a DOM when domhandler is attached as the handler.
What is the best HTML parser?
The README does not rank parsers, but it draws a line: htmlparser2 is the fast and forgiving option, and readers who need strict HTML spec compliance are pointed at parse5. Which one fits depends on whether your output must match browser tree construction.
How can I parse HTML using C#?
htmlparser2 cannot answer this: it is a Node.js package published on npm, written in TypeScript and consumed from JavaScript. The README documents no C# binding or .NET entry point.
How to use HTML parser in Python?
htmlparser2 is not a Python library. Its README gives a single installation command, npm install htmlparser2, and its usage example is JavaScript imported from the htmlparser2 package.
Official sources
Add this badge to your README
If you maintain this project, the badge below links readers to this analysis and shows its maintenance status from the daily GitHub snapshot. Paste the markdown into your README; add ?metric=license or ?metric=stars to the image URL for a different field.
[](https://hysenlabs.com/projects/fb55-htmlparser2)Star history chart for your README
[](https://hysenlabs.com/projects/fb55-htmlparser2)Was this useful?