# JavaScript HTML parser libraries

JavaScript HTML parser libraries turn HTML text into a tree of nodes that code can query, change, and serialize. A full DOM implementation exposes browser APIs such as querySelector, while a lighter parser returns a plain tree or a stream of parse events. These libraries extract data from scraped pages, transform HTML in build pipelines, and run browser-style tests.

## Popularity

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [parse5](#parse) | 910.8M | 3.9K | Nov 2026 | MIT |
| [jsdom](#jsdom) | 603.4M | 21.8K | Nov 2026 | MIT |
| [htmlparser2](#htmlparser) | 542.3M | 4.8K | Mar 2026 | MIT |
| [Cheerio](#cheerio) | 138.0M | 30.5K | Jan 2026 | MIT |
| [Happy DOM](#happy-dom) | 130.1M | 4.8K | Oct 2026 | MIT |
| [html-parse-stringify](#html-parse-stringify) | 92.9M | 3 | Jul 2026 | MIT |
| [hast-util-from-html](#hast-util-from-html) | 83.9M | 42 | Nov 2026 | MIT |
| [node-html-parser](#node-html-parser) | 57.8M | 1.2K | Nov 2026 | MIT |

Downloads: npm, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

[parse5](#parse) has the most monthly downloads in this comparison, at 910.8M.

## Capabilities

| Library | Native CSS selectors | Original source offsets |
| --- | --- | --- |
| [parse5](#parse) | No | Yes |
| [jsdom](#jsdom) | Yes | Yes |
| [htmlparser2](#htmlparser) | No | Yes |
| [Cheerio](#cheerio) | Yes | Yes |
| [Happy DOM](#happy-dom) | Yes | No |
| [html-parse-stringify](#html-parse-stringify) | No | No |
| [hast-util-from-html](#hast-util-from-html) | No | Yes |
| [node-html-parser](#node-html-parser) | Yes | Yes |

## Libraries

### parse5

[GitHub](https://github.com/inikulin/parse5) · [npm](https://www.npmjs.com/package/parse5) · [Docs](https://parse5.js.org/)

Parses and serializes HTML using the WHATWG HTML standard.

- Downloads / mo: 910.8M
- Stars: 3.9K
- Last release: 8.1.1
- License: MIT
- Capabilities: [From the parse5 docs](https://parse5.js.org/)

**Strengths**

- **Uses browser parsing rules.** Build HTML trees using the HTML Living Standard.
- **Parses fragments with context.** Pass a context element to parse fragment content as innerHTML.

**Watch out for**

- **Inserted nodes lack source locations.** Implicitly created tree-correction elements have undefined sourceCodeLocation.
- **Streaming needs another package.** Install parse5-parser-stream for the streaming parser.

```sh
npm install parse5
```

**tt-a1i/archify** (97.2K stars)

[tt-a1i/archify](https://github.com/tt-a1i/archify) 

```typescript
export function localizeHtml(html, { lang, page, cloudflare, copy = {} }) {
  const tree = parseFragment(html);
  function walk(node) {
    const attrs = new Map((node.attrs || []).map(item => [item.name, item]));
    const get = name => attrs.get(name)?.value;
    const set = (name, value) => {
      if (attrs.has(name)) attrs.get(name).value = value;
      else { const attr = { name, value }; node.attrs.push(attr); attrs.set(name, attr); }
    };
    if (node.tagName === 'script' && get('src') === 'assets/site-language.js') {
      node.parentNode.childNodes = node.parentNode.childNodes.filter(child => child !== node);
      return;
    }
    const key = get('data-i18n') || get('data-i18n-html');
    const value = key ? copy[lang]?.[key] : get(`data-${lang}`);
    if (typeof value === 'string') {
      // Only authored dictionary strings or explicit markup may contain HTML.
      const markup = key || get('data-translation-html') !== undefined || page === 'gallery';
      node.childNodes = markup ? parseFragment(value).childNodes : [{ nodeName: '#text', value, parentNode: node }];
      for (const child of node.childNodes) child.parentNode = node;
    }
    const placeholder = copy[lang]?.[get('data-i18n-placeholder')];
    if (typeof placeholder === 'string') set('placeholder', placeholder);
    if (get('data-language-switch') !== undefined) {
      set('href', localPagePath(page, lang === 'zh' ? 'en' : 'zh', cloudflare));
      set('hreflang', lang === 'zh' ? 'en' : 'zh-Hans');
      set('aria-label', lang === 'zh' ? 'Switch to English' : '切换到中文');
      node.childNodes = [{ nodeName: '#text', value: lang === 'zh' ? 'EN' : '中文', parentNode: node }];
    } else if (node.tagName === 'a') {
      const href = get('href');
      const match = href?.match(/^(?:(index|guide|start|gallery|community|agent-diagrams|compare|cases\/mco-runtime)\.html|(\.\/))([?#].*)?$/);
      if (match) set('href', localPagePath(match[1] || 'index', lang, cloudflare) + (match[3] || ''));
      else if (href?.startsWith('#')) set('href', localPagePath(page, lang, cloudflare) + href);
    }
    for (const child of [...(node.childNodes || [])]) walk(child);
  }
  walk(tree);
  return serialize(tree);
}

```

[website/src/data/localize-html.mjs](https://github.com/tt-a1i/archify/blob/a7ed6fd6657da90414831d1d42cf95987188750c/website/src/data/localize-html.mjs#L4-L42) · [More projects using parse5 →](https://dashboard.exa.ai/playground/search?q=Projects%20using%20parse5%20to%20parse%2C%20inspect%20and%20transform%20HTML&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```typescript
import { parse } from 'parse5';

const document = parse('<p>Hello</p>');

```

From [index.ts](https://cdn.jsdelivr.net/npm/parse5@8.1.1/dist/index.d.ts)

### jsdom

[GitHub](https://github.com/jsdom/jsdom) · [npm](https://www.npmjs.com/package/jsdom) · [Docs](https://raw.githubusercontent.com/jsdom/jsdom/main/README.md)

Provides DOM objects for working with parsed HTML in Node.js.

- Downloads / mo: 603.4M
- Stars: 21.8K
- Last release: 31.0.1
- License: MIT
- Capabilities: [From the jsdom docs](https://raw.githubusercontent.com/jsdom/jsdom/main/README.md)

**Strengths**

- **Exposes familiar DOM selectors.** Use document.querySelector on the parsed document.
- **Retains optional source locations.** Enable includeNodeLocations and retrieve positions with nodeLocation.

**Watch out for**

- **Layout measurements are incomplete.** Layout-related properties can return zeros instead of browser measurements.
- **Link navigation stays unimplemented.** Changing location.href does not create a new document.

```sh
npm install jsdom
```

**Quickstart**

```typescript
const { JSDOM } = require('jsdom');

const dom = new JSDOM('<p>Hello</p>');
const text = dom.window.document.querySelector('p').textContent;

```

From [README.md](https://raw.githubusercontent.com/jsdom/jsdom/main/README.md) · [Find projects using jsdom →](https://dashboard.exa.ai/playground/search?q=Projects%20using%20jsdom%20to%20parse%2C%20inspect%20and%20transform%20HTML&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

### htmlparser2

[GitHub](https://github.com/fb55/htmlparser2) · [npm](https://www.npmjs.com/package/htmlparser2) · [Docs](https://github.com/fb55/htmlparser2/blob/master/README.md)

Parses HTML and XML using event callbacks or a document tree.

- Downloads / mo: 542.3M
- Stars: 4.8K
- Last release: 12.0.0
- License: MIT
- Capabilities: [From the htmlparser2 docs](https://github.com/fb55/htmlparser2/blob/master/README.md)

**Strengths**

- **Processes input in chunks.** Feed markup through Parser.write before ending the input.
- **Serializes edited trees.** Use the exported DomUtils.getOuterHTML to serialize changed HTML.

**Watch out for**

- **Browser tree rules differ.** Choose parse5 when strict HTML specification compliance matters.
- **Text callbacks can split content.** Join text pieces when one callback does not contain the whole section.

```sh
npm install htmlparser2
```

**Quickstart**

```typescript
import { parseDocument } from 'htmlparser2';

const document = parseDocument('<p>Hello</p>');

```

From [README.md](https://cdn.jsdelivr.net/npm/htmlparser2@12.0.0/dist/index.d.ts) · [Find projects using htmlparser2 →](https://dashboard.exa.ai/playground/search?q=Projects%20using%20htmlparser2%20to%20parse%2C%20inspect%20and%20transform%20HTML&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

### Cheerio

[GitHub](https://github.com/cheeriojs/cheerio) · [npm](https://www.npmjs.com/package/cheerio) · [Docs](https://cheerio.js.org/docs/intro)

Parses HTML and XML with a jQuery-like selection and editing API.

- Downloads / mo: 138.0M
- Stars: 30.5K
- Last release: 1.2.0
- License: MIT
- Capabilities: [From the Cheerio docs](https://cheerio.js.org/docs/intro)

**Strengths**

- **Selects elements with CSS.** Call the returned dollar function with a CSS selector.
- **Reads byte streams with encoding.** Use decodeStream when the source encoding is unknown.

**Watch out for**

- **Client-rendered content stays absent.** Cheerio does not execute the scripts that create client-rendered content.
- **Browser builds only load strings.** Buffer, stream, and URL loaders require Node.js.

```sh
npm install cheerio
```

**langchain-ai/langchainjs** (18.3K stars)

[langchain-ai/langchainjs](https://github.com/langchain-ai/langchainjs) 

```typescript
static async _scrape(
    url: string,
    caller: AsyncCaller,
    timeout: number | undefined,
    textDecoder?: TextDecoder,
    options?: CheerioOptions
  ): Promise<CheerioAPI> {
    const { load } = await CheerioWebBaseLoader.imports();
    const response = await caller.call(fetch, url, {
      signal: timeout ? AbortSignal.timeout(timeout) : undefined,
    });
    const html =
      textDecoder?.decode(await response.arrayBuffer()) ??
      (await response.text());
    return load(html, options);
  }

```

[langchain/src/document_loaders/web/cheerio.ts](https://github.com/langchain-ai/langchainjs/blob/44ede93dd92e0515e56948f7b35a5fe0240e60bf/langchain/src/document_loaders/web/cheerio.ts#L96-L111) · [More projects using Cheerio →](https://dashboard.exa.ai/playground/search?q=Projects%20using%20cheerio%20to%20parse%2C%20inspect%20and%20transform%20HTML&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```typescript
import * as cheerio from 'cheerio';

const $ = cheerio.load('<h1>Hello</h1>');
const text = $('h1').text();

```

From [Readme.md](https://cheerio.js.org/docs/intro)

### Happy DOM

[GitHub](https://github.com/capricorn86/happy-dom) · [npm](https://www.npmjs.com/package/happy-dom) · [Docs](https://github.com/capricorn86/happy-dom/wiki/Browser)

Implements a web browser without a graphical interface, including many WHATWG DOM and HTML standards.

- Downloads / mo: 130.1M
- Stars: 4.8K
- Last release: 21.0.4
- License: MIT
- Capabilities: [From the Happy DOM docs](https://github.com/capricorn86/happy-dom/wiki/Browser)

**Strengths**

- **Simulates a browser or a window.** The Browser class loads pages, while the Window class builds a DOM directly.
- **Supports custom elements.** Custom elements with declarative shadow DOM work inside the simulated document.

**Watch out for**

- **Scripts are off by default.** Turn on JavaScript evaluation only for trusted code, because its VM contexts are not isolated.

```sh
npm install happy-dom
```

**Quickstart**

```javascript
import { Window } from 'happy-dom';

const window = new Window();
window.document.body.innerHTML = '<p>Hello</p>';
const text = window.document.querySelector('p').textContent;
await window.happyDOM.close();

```

From [Window.md](https://github.com/capricorn86/happy-dom/wiki/Window) · [Find projects using Happy DOM →](https://dashboard.exa.ai/playground/search?q=happy-dom%20GitHub%20projects)

### html-parse-stringify

[GitHub](https://github.com/i18next/html-parse-stringify) · [npm](https://www.npmjs.com/package/html-parse-stringify) · [Docs](https://github.com/i18next/html-parse-stringify/blob/master/README.md)

Parses well-formed HTML, with every tag closed, into an AST and back.

- Downloads / mo: 92.9M
- Stars: 3
- Last release: 4.0.1
- License: MIT
- Capabilities: [From the html-parse-stringify docs](https://github.com/i18next/html-parse-stringify/blob/master/README.md)

**Strengths**

- **Round-trips HTML strings.** Stringify turns the parsed AST back into the original HTML string.
- **Powers the Trans component.** The i18next community maintains it as the parser behind Trans in react-i18next.

**Watch out for**

- **Requires closed tags.** Close or self-close every tag before parsing.

```sh
npm install html-parse-stringify
```

**drl990114/MarkFlowy** (2.4K stars)

[drl990114/MarkFlowy](https://github.com/drl990114/MarkFlowy) 

```javascript
async () => {
        return new Promise<string>((resolve) => {
          let targetDoc: Node | string = otherProps.content

          if (typeof targetDoc === 'string') {
            targetDoc = createWysiwygDelegate(otherProps.delegateOptions).stringToDoc(targetDoc)
          }

          const html = prosemirrorNodeToHtml(targetDoc)

          const fullAst = HTML.parse(html)

          const imageLoadTasks: Promise<void>[] = []
          const handleHtmlText = async (ast: HTMLAstNode[]) => {
            const handleNode = (node: HTMLAstNode) => {
              if (!node) {
                return
              }

              if (
                node.name === 'img' &&
                node.attrs?.src &&
                otherProps.delegateOptions?.handleViewImgSrcUrl
              ) {
                imageLoadTasks.push(
                  (async () => {
                    node.attrs.src = await otherProps.delegateOptions?.handleViewImgSrcUrl?.(
                      node.attrs.src,
                    )
                    node.attrs.key = nanoid()
                  })(),
                )
              }

              if (node.children) {
                handleHtmlText(node.children)
              }
            }

            for (let i = 0; i < ast.length; i++) {
              handleNode(ast[i])
            }
          }

          handleHtmlText(fullAst)
          Promise.all(imageLoadTasks)
            .then(() => {
              resolve(HTML.stringify(fullAst))
            })
            .catch(() => {
              resolve(html)
            })
        })
      }

```

[packages/editor/src/editor/components/Editor.tsx](https://github.com/drl990114/MarkFlowy/blob/fbf8c9be1d7cbce487750313c572af77415013e4/packages/editor/src/editor/components/Editor.tsx#L115-L168) · [More projects using html-parse-stringify →](https://dashboard.exa.ai/playground/search?q=html-parse-stringify%20GitHub%20projects)

**Quickstart**

```javascript
import HTML from 'html-parse-stringify';

const nodes = HTML.parse('<p>Hello</p>');

```

From [README.md](https://github.com/i18next/html-parse-stringify/blob/master/README.md)

### hast-util-from-html

[GitHub](https://github.com/syntax-tree/hast-util-from-html) · [npm](https://www.npmjs.com/package/hast-util-from-html) · [Docs](https://github.com/syntax-tree/hast-util-from-html/blob/main/readme.md)

Turns HTML into a hast syntax tree.

- Downloads / mo: 83.9M
- Stars: 42
- Last release: 2.1.0
- License: MIT
- Capabilities: [From the hast-util-from-html docs](https://github.com/syntax-tree/hast-util-from-html/blob/main/readme.md)

**Strengths**

- **Parses fragments or documents.** Set fragment to true to parse a snippet instead of a whole document.
- **Records detailed positions.** The verbose option records positions for attributes, start tags, and end tags.

**Watch out for**

- **Output is not sanitized.** Run hast-util-sanitize on the tree before rendering user-provided HTML.

```sh
npm install hast-util-from-html
```

**rehypejs/rehype** (2.3K stars)

[rehypejs/rehype](https://github.com/rehypejs/rehype) 

```javascript
function parser(document, file) {
  return fromHtml(document, {
    ...settings,
    onerror: emitParseErrors
      ? function (message) {
          if (file.path) {
            message.name = file.path + ':' + message.name
            message.file = file.path
          }

          file.messages.push(message)
        }
      : undefined
  })
}

```

[packages/rehype-parse/lib/index.js](https://github.com/rehypejs/rehype/blob/cae74c7f729a55c6f407bdb95aaa362b44e7c2c2/packages/rehype-parse/lib/index.js#L54-L68) · [More projects using hast-util-from-html →](https://dashboard.exa.ai/playground/search?q=hast-util-from-html%20GitHub%20projects)

**Quickstart**

```javascript
import { fromHtml } from 'hast-util-from-html';

const tree = fromHtml('<p>Hello</p>', { fragment: true });

```

From [readme.md](https://github.com/syntax-tree/hast-util-from-html/blob/main/readme.md)

### node-html-parser

[GitHub](https://github.com/taoqf/node-html-parser) · [npm](https://www.npmjs.com/package/node-html-parser) · [Docs](https://github.com/taoqf/node-html-parser/blob/main/README.md)

Parses HTML into a simplified DOM tree with element queries.

- Downloads / mo: 57.8M
- Stars: 1.2K
- Last release: 9.0.7
- License: MIT
- Capabilities: [From the node-html-parser docs](https://github.com/taoqf/node-html-parser/blob/main/README.md)

**Strengths**

- **Supports querySelector.** Query the parsed tree with CSS selectors through querySelector.
- **Serializes back to HTML.** Call toString on the root to write the tree back out as HTML.

**Watch out for**

- **Some malformed HTML misparses.** Expect parse errors on some malformed HTML beyond common cases such as unclosed table cells.

```sh
npm install node-html-parser
```

**Mintplex-Labs/anything-llm** (68.4K stars)

[Mintplex-Labs/anything-llm](https://github.com/Mintplex-Labs/anything-llm) 

```javascript
function resolveUrls(root, baseUrl) {
  for (const a of root.querySelectorAll("a[href]")) {
    const href = a.getAttribute("href");
    if (!href || /^(https?:|mailto:|tel:|javascript:|#)/i.test(href)) continue;
    try {
      a.setAttribute("href", new URL(href, baseUrl).toString());
    } catch {}
  }

  for (const img of root.querySelectorAll("img[src]")) {
    const src = img.getAttribute("src");
    if (!src) {
      img.remove();
      continue;
    }
    if (src.startsWith("data:")) {
      img.remove();
      continue;
    }

    const resolvedSrc = /^https?:/i.test(src)
      ? src
      : (() => {
          try {
            return new URL(src, baseUrl).toString();
          } catch {
            return src;
          }
        })();

    if (IGNORED_IMG_BASEPATHS.some((base) => resolvedSrc.startsWith(base))) {
      img.remove();
      continue;
    }

    if (!/^https?:/i.test(src)) {
      try {
        img.setAttribute("src", new URL(src, baseUrl).toString());
      } catch {}
    }

    const alt = (img.getAttribute("alt") || "").trim();
    if (!alt) {
      try {
        const pathname = new URL(img.getAttribute("src")).pathname;
        const filename = pathname.split("/").pop() || "image";
        img.setAttribute("alt", filename);
      } catch {
        img.setAttribute("alt", "image");
      }
    }
  }
}

```

[collector/processLink/helpers/htmlToMarkdown.js](https://github.com/Mintplex-Labs/anything-llm/blob/2f6a451f55aca970311af2579088fe0c27af3ce8/collector/processLink/helpers/htmlToMarkdown.js#L423-L475) · [More projects using node-html-parser →](https://dashboard.exa.ai/playground/search?q=node-html-parser%20GitHub%20projects)

**Quickstart**

```javascript
import { parse } from 'node-html-parser';

const root = parse('<p>Hello</p>');
const text = root.querySelector('p').textContent;

```

From [README.md](https://github.com/taoqf/node-html-parser/blob/main/README.md)

## FAQ

### Which JavaScript HTML parser should I use?

parse5 follows the HTML Living Standard and fits code that needs browser-accurate trees. Cheerio adds a jQuery-like API for selecting and editing elements. jsdom and Happy DOM supply a DOM with browser APIs, while htmlparser2 emits parse events as markup arrives.

### What is Cheerio?

Cheerio parses HTML and XML and gives a jQuery-like API for traversing and changing the result. It does not render pages, load external resources, or run JavaScript.

### What is jsdom?

jsdom is a pure-JavaScript implementation of the WHATWG DOM and HTML standards for Node.js. It returns zeros for many layout properties and does not navigate when location.href changes.

### jsdom vs Cheerio: which should I use?

Cheerio parses markup into a tree with a jQuery-like API and skips rendering, CSS, and scripts. jsdom builds a browser-style DOM, with objects such as window and document.querySelector.

### What is Happy DOM?

Happy DOM implements a web browser without a graphical interface, including many WHATWG DOM and HTML standards. It works as a test environment for tools such as Vitest and Jest, and it runs scripts only when JavaScript evaluation is turned on.

### Can Cheerio read content that page scripts create?

No. Content that client-side scripts render never reaches Cheerio's tree, because Cheerio does not run JavaScript.

## How this page was built

Data checked Nov 20, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Best JavaScript HTML parser libraries Cheerio jsdom parse5 htmlparser2 code examples",
    "numResults": 5
  }
}
```

Docs: https://exa.ai/docs/reference/search
