Profile
Back to NewsBack
GitHub Trending 4 min
Reader Mode
remarkablemark/html-dom-parser: 📝 HTML to DOM parser.

remarkablemark/html-dom-parser: 📝 HTML to DOM parser.

8 hours ago

html-dom-parser

NPM</a>

NPM version</a> NPM bundle size</a> build</a> codecov</a> NPM downloads</a>

HTML to DOM parser that works on both the server (Node.js) and the client (browser):

HTMLDOMParser(string[, options])

The parser converts an HTML string to a JavaScript object that describes the DOM tree.

For example:

import parse from 'html-dom-parser';

parse('<p>Hello, World!</p>');

Output

[
  Element {
    type: 'tag',
    parent: null,
    prev: null,
    next: null,
    startIndex: null,
    endIndex: null,
    children: [
      Text {
        type: 'text',
        parent: [Circular],
        prev: null,
        next: null,
        startIndex: null,
        endIndex: null,
        data: 'Hello, World!'
      }
    ],
    name: 'p',
    attribs: {}
  }
]

StackBlitz | JSFiddle | Examples

Install

NPM:

npm install html-dom-parser --save

Yarn:

yarn add html-dom-parser

CDN:

<script src="https://unpkg.com/html-dom-parser@latest/dist/html-dom-parser.min.js"></script>
<script>
  window.HTMLDOMParser(/ string /);
</script>

Usage

Import with ES Modules:

import parse from 'html-dom-parser';

Require with CommonJS:

const parse = require('html-dom-parser').default;

Parse empty string:

parse('');

Output:

[]

Parse string:

parse('Hello, World!');

Output

[
  Text {
    type: 'text',
    parent: null,
    prev: null,
    next: null,
    startIndex: null,
    endIndex: null,
    data: 'Hello, World!'
  }
]

Parse element with attributes:

parse('<p class="foo" style="color: #bada55">Hello, <em>world</em>!</p>');

Output

[
  Element {
    type: 'tag',
    parent: null,
    prev: null,
    next: null,
    startIndex: null,
    endIndex: null,
    children: [ [Text], [Element], [Text] ],
    name: 'p',
    attribs: { class: 'foo', style: 'color: #bada55' }
  }
]

The server parser is a wrapper of htmlparser2 parseDOM but with the root parent node excluded. The next section shows the available options you can use with the server parse.

The client parser mimics the server parser by using the DOM API to parse the HTML string.

Options

Browser

trustedTypePolicy

When running in a browser, you can pass a Trusted Types policy so the parser calls trustedTypePolicy.createHTML before assigning content to innerHTML:

parse('<div>Hello</div>', {
  trustedTypePolicy: window.trustedTypes?.createPolicy('my-policy', {
    createHTML(input) {
      // apply sanitization logic here
      return DOMPurify.sanitize(input);
    },
  }),
});

Server

Because the server parser is a wrapper of htmlparser2, which implements domhandler, you can alter how the server parser parses your code with the options:

export interface ParserOptions {
  /**
   * Indicates whether special tags (<script>, <style>, and <title>) should get special treatment
   * and if "empty" tags (eg. <br>) can have children.  If false, the content of special tags
   * will be text only. For feeds and other XML content (documents that don't consist of HTML),
   * set this to true.
   *
   * @default false
   */
  xmlMode?: boolean;

/** * Decode entities within the document. * * @default true */ decodeEntities?: boolean;

/** * If set to true, all tags will be lowercased. * * @default !xmlMode */ lowerCaseTags?: boolean;

/** * If set to true, all attribute names will be lowercased. This has noticeable impact on speed. * * @default !xmlMode */ lowerCaseAttributeNames?: boolean;

/** * If set to true, CDATA sections will be recognized as text even if the xmlMode option is not enabled. * NOTE: If xmlMode is set to true then CDATA sections will always be recognized as text. * * @default xmlMode */ recognizeCDATA?: boolean;

/** * If set to true, self-closing tags will trigger the onclosetag event even if xmlMode is not set to true. * NOTE: If xmlMode is set to true then self-closing tags will always be recognized. * * @default xmlMode */ recognizeSelfClosing?: boolean;

/** * Allows the default tokenizer to be overwritten. */ Tokenizer?: typeof Tokenizer; }

If you're parsing SVG, you can set lowerCaseTags to true without having to enable xmlMode. This will return all tag names in camelCase and not the HTML standard of lowercase.

[!NOTE]
If you're parsing code client-side (in-browser), you cannot control the parsing options. Client-side parsing automatically handles returning some HTML tags in camelCase, such as specific SVG elements, but returns all other tags lowercased according to the HTML standard.

Migration

v8

Changed build output to target ES6 instead of ES5.

v7

Upgraded htmlparser2.

v6

Upgraded domhandler and htmlparser2. Removed client exports formatAttributes and CARRIAGE_RETURN constants.

v5

Migrated to TypeScript. CommonJS imports require the .default key:

const parse = require('html-dom-parser').default;

v4

Upgraded htmlparser2.

v3

Upgraded domhandler. Parser options like normalizeWhitespace have been removed.

v2

Removed Internet Explorer (IE11) support.

v1

Upgraded domhandler and htmlparser2.

Release

Release and publish are automated by Release Please.

Special Thanks

License

MIT

Chat with me