@asamuzakjp/dom-selector

中文文档
10.0.5发布于 2026/10/23MITTypeScriptES Module近 30 天下载 2.3亿

A CSS selector engine.

原始使用文档
文档目录16 节
  1. Features
  2. Install
  3. Usage
  4. API
  5. new DOMSelector(window, document?, opt?)
  6. matches(selector, node, opt?)
  7. closest(selector, node, opt?)
  8. querySelector(selector, node, opt?)
  9. querySelectorAll(selector, node, opt?)
  10. check(selector, node, opt?)
  11. extractSubjects(selector, caseSensitive?)
  12. supports(selector)
  13. clear(clearAll?)
  14. Supported CSS selectors
  15. Performance
  16. Acknowledgments

DOM Selector

build CodeQL npm (scoped)

A CSS selector engine built for strict specification compliance.

Features

  • Strict Specification Compliance: Strictly adheres to modern web standards. It accurately parses, evaluates, and extracts elements across complex combinations of pseudo-classes and HTML attributes. Features comprehensive support for CSS Selectors Level 4 (e.g., :is(), :not(), :where(), :has()) and Shadow DOM pseudo-classes (:host, :host-context).
  • Utility Functions: Provides utility methods alongside standard querying, such as check() for AST evaluation and extractSubjects() for extracting subject keys from selectors.
  • jsdom's Default Engine: Adopted as the CSS selector engine for jsdom.

Install

npm i @asamuzakjp/dom-selector

Usage

import { DOMSelector } from '@asamuzakjp/dom-selector';
import { JSDOM } from 'jsdom';

const { window } = new JSDOM();

// Destructuring methods (all methods are bound to the instance)
const {
  check, closest, extractSubjects, matches, querySelector, querySelectorAll, supports
} = new DOMSelector(window);

API

new DOMSelector(window, document?, opt?)

Creates an instance of the DOMSelector.

  • window {Window} The window object.
  • document {Document}? The document object. Defaults to window.document.
  • opt {object}? Options:
    • opt.cacheSize {number}? Maximum number of items to store in the internal LRU cache. Defaults to 4096. This applies to every internal cache, including the per-document cache that pairs parsed selectors with a document, so that repeatedly querying distinct selectors on a live document does not grow its cache without limits.
    • opt.idlUtils {object}? The internal IDL wrapper used for jsdom.
    • opt.maxLength {number}? The maximum length of the selector allowed. Defaults to 2048.

matches(selector, node, opt?)

Equivalent to Element.matches().

  • selector {string} CSS selector.
  • node {Element} Element node.
  • opt {object}? Options:
    • opt.noexcept {boolean}? true to suppress exceptions (e.g., DOMException for invalid selectors) and return false instead.
    • opt.warn {boolean}? true to output warnings to the console when encountering unsupported or deprecated features.
  • Returns {boolean} true if matched, false otherwise.

closest(selector, node, opt?)

Equivalent to Element.closest().

  • selector {string} CSS selector.
  • node {Element} Element node.
  • opt {object}? Options:
    • opt.noexcept {boolean}? true to suppress exceptions and return null instead.
    • opt.warn {boolean}? true to output warnings to the console when encountering unsupported or deprecated features.
  • Returns {Element | null} The matched ancestor node or null.

querySelector(selector, node, opt?)

Equivalent to Document.querySelector(), DocumentFragment.querySelector() and Element.querySelector().

  • selector {string} CSS selector.
  • node {Document | DocumentFragment | Element} Node to find within.
  • opt {object}? Options:
    • opt.noexcept {boolean}? true to suppress exceptions and return null instead.
    • opt.warn {boolean}? true to output warnings to the console when encountering unsupported or deprecated features.
  • Returns {Element | null} The matched node or null.

querySelectorAll(selector, node, opt?)

Equivalent to Document.querySelectorAll(), DocumentFragment.querySelectorAll() and Element.querySelectorAll(). NOTE: Returns a standard Array<Element>, not a NodeList.

  • selector {string} CSS selector.
  • node {Document | DocumentFragment | Element} Node to find within.
  • opt {object}? Options:
    • opt.noexcept {boolean}? true to suppress exceptions and return an empty array [] instead.
    • opt.warn {boolean}? true to output warnings to the console when encountering unsupported or deprecated features.
  • Returns {Array} Array of matched elements.

check(selector, node, opt?)

Checks if an element matches a CSS selector and returns additional abstract syntax tree (AST) information. NOTE: Any pseudo-elements in the selector are excluded from the matching evaluation.

  • selector {string} CSS selector.
  • node {Element} Element node.
  • opt {object}? Options:
    • opt.requireAst {boolean}? Indicates whether to always try to parse and return the AST.
    • opt.noexcept {boolean}? true to suppress exceptions and store the error in the error property of the result instead of throwing.
    • opt.warn {boolean}? true to output warnings to the console when encountering unsupported or deprecated features.
  • Returns {CheckResult} An object containing the following properties:
    • match {boolean} true if the element matches the selector, false otherwise.
    • pseudoElement {string | null} The pseudo-element extracted from the selector, if any.
    • ast {object | null} The parsed AST object.
    • error {DOMException | Error | null} The error object, if any.

extractSubjects(selector, caseSensitive?)

Parses a selector and extracts the rightmost subject keys (Id, Class, Tag).

  • selector {string} CSS selector.
  • caseSensitive {boolean}? true if the tag key should be case sensitive. Defaults to false.
  • Returns {Array} An array of extracted subject keys. Each object contains:
    • id {string | null} The ID.
    • className {string | null} The class name.
    • tag {string | null} The tag name.

supports(selector)

Checks if the given CSS selector is supported by this engine. See the table below for the full list of supported selectors.

  • selector {string} CSS selector.
  • Returns {boolean} true if the selector is supported, false otherwise.

clear(clearAll?)

Clears the internal caches to free up memory.

  • clearAll {boolean}? Whether to clear all caches. If false, only cached matching results are cleared. Defaults to false.
  • Returns {void}

Supported CSS selectors

PatternSupportedNote
*✓
E✓
ns|E✓
*|E✓
|E✓
E F✓
E > F✓
E + F✓
E ~ F✓
F || EUnsupported
E.warning✓
E#myid✓
E[foo]✓
E[foo="bar"]✓
E[foo="bar" i]✓
E[foo="bar" s]✓
E[foo~="bar"]✓
E[foo^="bar"]✓
E[foo$="bar"]✓
E[foo*="bar"]✓
E[foo|="en"]✓
E:is(s1, s2, …)✓
E:not(s1, s2, …)✓
E:where(s1, s2, …)✓
E:has(rs1, rs2, …)✓
E:definedPartially supportedMatching with MathML is not yet supported.
E:dir(ltr)✓
E:lang(en)✓
E:any-link✓
E:link✓
E:visited✓Returns false or null to prevent fingerprinting.
E:local-link✓
E:target✓
E:target-withinRemoved from spec.
E:scope✓
E:hover✓
E:active✓
E:focus✓
E:focus-visible✓
E:focus-within✓
E:currentUnsupported
E:current(s)Unsupported
E:pastUnsupported
E:futureUnsupported
E:openPartially supportedMatching with <select>, e.g. select:open, or <input type="color"> are not supported.
E:popover-openUnsupported
E:enabled
E:disabled
✓
E:read-write
E:read-only
✓
E:placeholder-shown✓
E:default✓
E:checked✓
E:indeterminate✓
E:blankUnsupported
E:valid
E:invalid
✓
E:in-range
E:out-of-range
✓
E:required
E:optional
✓
E:user-valid
E:user-invalid
Unsupported
E:root✓
E:empty✓
E:nth-child(n [of S]?)✓
E:nth-last-child(n [of S]?)✓
E:first-child✓
E:last-child✓
E:only-child✓
E:nth-of-type(n)✓
E:nth-last-of-type(n)✓
E:first-of-type✓
E:last-of-type✓
E:only-of-type✓
E:nth-col(n)Unsupported
E:nth-last-col(n)Unsupported
CE:state(v)✓*1
:host✓
:host(s)✓
:host(:state(v))✓*1
:host:has(rs1, rs2, ...)✓
:host(s):has(rs1, rs2, ...)✓
:host-context(s)✓
:host-context(s):has(rs1, rs2, ...)✓
&✓Only supports outermost &, i.e. equivalent to :scope

*1: ElementInternals.states, i.e. CustomStateSet, is not implemented in jsdom, so you need to apply a patch in the custom element constructor.

class LabeledCheckbox extends window.HTMLElement {
  #internals;
  constructor() {
    super();
    this.#internals = this.attachInternals();
    // patch CustomStateSet
    if (!this.#internals.states) {
      this.#internals.states = new Set();
    }
    this.addEventListener('click', this._onClick.bind(this));
  }
  get checked() {
    return this.#internals.states.has('checked');
  }
  set checked(flag) {
    if (flag) {
      this.#internals.states.add('checked');
    } else {
      this.#internals.states.delete('checked');
    }
  }
  _onClick(event) {
    this.checked = !this.checked;
  }
}

Performance

See benchmark for the latest results.

Acknowledgments

The following resources have been of great help in the development of the DOM Selector.


Copyright (c) 2023 asamuzaK (Kazz)

版本与发布记录

@asamuzakjp/dom-selector 共发布 288 个版本,首次发布于 2023/05/07;过去 12 个月发布了 59 个版本。

版本发布日期距今
10.0.5latest2026/10/2315 天前
10.0.42026/10/1721 天前
10.0.32026/10/1524 天前
10.0.22026/10/1325 天前
10.0.12026/10/1028 天前
10.0.02026/10/1028 天前

其他发布通道:beta → 0.2.2,dev → 6.5.0-a.16,next → 8.0.0-a.2。

关于 @asamuzakjp/dom-selector 的常见问题

@asamuzakjp/dom-selector 是什么?

A CSS selector engine.

如何安装 @asamuzakjp/dom-selector?

在项目目录运行 npm install @asamuzakjp/dom-selector,或使用 pnpm add / yarn add / bun add。

@asamuzakjp/dom-selector 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@asamuzakjp/dom-selector 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@asamuzakjp/dom-selector 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js ^22.22.2 || ^24.15.0 || >=26.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@asamuzakjp/dom-selector 可以商用吗?

@asamuzakjp/dom-selector 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@asamuzakjp/dom-selector 的下载量有多少?

根据 npm 官方下载统计,@asamuzakjp/dom-selector 在 2026/10/07 – 2026/11/05 这 30 天内被下载 228,426,597 次,日均约 7,614,220 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@asamuzakjp/dom-selector 还在维护吗?

最新版本 10.0.5 发布于 2026/10/23(15 天前);至今共发布 288 个版本,其中过去 12 个月发布了 59 个;首次发布于 2023/05/07。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。