Skip to main content

Overview

The filter property of a rule determines which HTML elements the rule applies to. Filters can be strings, arrays, or functions, providing flexibility for simple and complex matching logic.

Filter Types

String Filter

Matches a single HTML element by tag name (case-insensitive). Example - Paragraph:
Matches all <p> elements. Example - Blockquote:
Matches all <blockquote> elements. Example - Line Break:
Matches all <br> elements.

Array Filter

Matches multiple HTML elements by tag names. Example - Emphasis:
Matches both <em> and <i> elements. Example - Strong:
Matches both <strong> and <b> elements. Example - Headings:
Matches all heading elements from <h1> through <h6>. Example - Lists:
Matches both unordered (<ul>) and ordered (<ol>) lists.

Function Filter

A function that receives a DOM node and options object, and returns true if the rule should apply to that node. Returns: boolean - true if the rule should apply to this node

Example: Inline Code

Matches <code> elements that are NOT inside <pre> blocks:
This filter:
  1. Checks if the node is a <code> element
  2. Determines if it’s inside a <pre> block without siblings (which would be a code block)
  3. Returns true only for inline code, not code blocks

Example: Indented Code Block

Matches code blocks when the codeBlockStyle option is set to 'indented':
This filter:
  1. Checks the codeBlockStyle option
  2. Verifies the node is a <pre> element
  3. Confirms it contains a <code> child element

Example: Fenced Code Block

Matches code blocks when the codeBlockStyle option is set to 'fenced':
Similar to the indented code block filter, but for fenced code blocks. Matches links when the linkStyle option is set to 'inlined':
This filter:
  1. Checks if inline link style is enabled
  2. Verifies the node is an <a> element
  3. Ensures the link has an href attribute
Matches links when the linkStyle option is set to 'referenced':
Similar to inline links, but for reference-style links.

Filter Behavior

Case Sensitivity

Tag names in string and array filters are case-insensitive. The filter automatically converts them to lowercase for comparison:

Node Names

When checking node.nodeName in function filters, it returns the tag name in uppercase. Always compare using uppercase or convert to lowercase:

Filter Evaluation Order

Filters are evaluated in the order of rule precedence. The first matching filter’s replacement function is used.

Common Patterns

Checking Parent Elements

Checking Attributes

Checking Child Elements

Combining with Options

Usage with keep() and remove()

The keep() and remove() methods also accept filters: