# @asamuzakjp/dom-selector 中文文档

规范地址：https://npmcn.com/package/%40asamuzakjp/dom-selector/

版本：10\.0\.5
npm 元数据更新时间：2026-10-23T14:26:31.972Z
中文译文更新时间：2026-11-06T22:05:41.960Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40asamuzakjp/dom-selector
原文对照：https://npmcn.com/package/%40asamuzakjp/dom-selector/?lang=original
项目主页：https://github.com/asamuzaK/domSelector#readme
源码仓库：https://github.com/asamuzaK/domSelector

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：309 kB，33 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- Node.js 要求：^22\.22\.2 \|\| ^24\.15\.0 \|\| \>=26\.0\.0
- 运行依赖：4 个
- 首次发布：2023-05-07T08:07:57.013Z
- 最新版本发布：2026-10-23T14:26:31.572Z
- 近 30 天下载量：228426597（2026-10-07 至 2026-11-05，npm 官方下载统计）
- 已发布版本数：288（近 12 个月 59 个）

## 中文简介

CSS选择器引擎.

## 安装

```sh
npm install @asamuzakjp/dom-selector
```

也可以使用：`pnpm add @asamuzakjp/dom-selector`、`yarn add @asamuzakjp/dom-selector`、`bun add @asamuzakjp/dom-selector`

## README

# DOM 选择器

[![build](https://github.com/asamuzaK/domSelector/actions/workflows/node.js.yml/badge.svg)](https://github.com/asamuzaK/domSelector/actions/workflows/node.js.yml) [![CodeQL](https://github.com/asamuzaK/domSelector/actions/workflows/github-code-scanning/codeql/badge.svg)](https://github.com/asamuzaK/domSelector/actions/workflows/github-code-scanning/codeql) [![npm (scoped)](https://img.shields.io/npm/v/@asamuzakjp/dom-selector)](https://www.npmjs.com/package/@asamuzakjp/dom-selector)

为严格符合规格而建造的 CSS 选择器引擎.

## 特征

-   **严格规格合规性**:严格遵守现代网络标准. 它准确地剖析,评价,并取出元素跨越了伪类和HTML属性的复杂组合. CSS选择器4级(例如, `:is()`, (中文(简体) ), `:not()`, (中文(简体) ), `:where()`, (中文(简体) ), `:has()`)和"影子DOM"的伪类(`:host`, (中文(简体) ), `:host-context`) (中文(简体) ).
-   **工具函数**: 提供与标准查询并行的效用方法, 如 `check()` aST评价及 `extractSubjects()` 用于从选择器中提取主题密钥.
-   **jsdom 默认引擎**: 采用CSS选择引擎,用于 [日记](https://github.com/jsdom/jsdom)。 。 。 .

## 安装

```console
npm i @asamuzakjp/dom-selector
```

## 使用量

```javascript
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?)`

创建 DOMS 选择器实例 .

-   `window` **\[温道\]** 窗口对象 .
-   `document` **怎么样?** 文档对象 。 默认为 `window.document`。 。 。 .
-   `opt` **{对象}?** 选项 :
    -   `opt.cacheSize` **{数}?** 最多存储在 LRU 缓存中的项目 。 默认为 `4096`。这适用于每个内部缓存,包括每个文档缓存将解析选择器与文档对齐,这样在活文件上反复查询不同的选择器不会无限制地增大其缓存.
    -   `opt.idlUtils` **{对象}?** 用于jsdom的内部IDL包装器.
    -   `opt.maxLength` **{数}?** 选择器允许的最大长度 。 默认为 `2048`。 。 。 .

* * *

### `matches(selector, node, opt?)`

等值为 [元素. matches( )](https://developer.mozilla.org/docs/Web/API/Element/matches)。 。 。 .

-   `selector` **{\\fn黑体\\fs22\\bord1\\shad0\\3ahbe\\4ah00\\fscx67\\fscy66\\2chffffff\\3ch808080}你来干什么** CSS选取器.
-   `node` **{元素}** 元素节点.
-   `opt` **{对象}?** 选项 :
    -   `opt.noexcept` **怎么样?** `true` 禁止例外情况(例如, `DOMException` 用于无效选择)并返回 `false` 换句话说.
    -   `opt.warn` **怎么样?** `true` 当遇到不支持或贬值的特性时,向控制台输出警告.
-   **回返** **{布尔}** `true` 如果匹配, `false` 否则.

### `closest(selector, node, opt?)`

等值为 [元素. closest( )](https://developer.mozilla.org/docs/Web/API/Element/closest)。 。 。 .

-   `selector` **{\\fn黑体\\fs22\\bord1\\shad0\\3ahbe\\4ah00\\fscx67\\fscy66\\2chffffff\\3ch808080}你来干什么** CSS选取器.
-   `node` **{元素}** 元素节点.
-   `opt` **{对象}?** 选项 :
    -   `opt.noexcept` **怎么样?** `true` 禁止例外和返回 `null` 换句话说.
    -   `opt.warn` **怎么样?** `true` 当遇到不支持或贬值的特性时,向控制台输出警告.
-   **回返** **{元素} 无效}** 对应的祖先节点或 `null`。 。 。 .

### `querySelector(selector, node, opt?)`

等值为 [文档.query 选择器( )](https://developer.mozilla.org/docs/Web/API/Document/querySelector), (中文(简体) ), [DocumentFraft.query 选择器 ()](https://developer.mozilla.org/docs/Web/API/DocumentFragment/querySelector) 财务报告和审定财务报表 [元素.query 选择器( )](https://developer.mozilla.org/docs/Web/API/Element/querySelector)。 。 。 .

-   `selector` **{\\fn黑体\\fs22\\bord1\\shad0\\3ahbe\\4ah00\\fscx67\\fscy66\\2chffffff\\3ch808080}你来干什么** CSS选取器.
-   `node` **{文档{文档{文档碎片}{元素}** 节点可以在里面找到.
-   `opt` **{对象}?** 选项 :
    -   `opt.noexcept` **怎么样?** `true` 禁止例外和返回 `null` 换句话说.
    -   `opt.warn` **怎么样?** `true` 当遇到不支持或贬值的特性时,向控制台输出警告.
-   **回返** **{元素} 无效}** 匹配的节点或 `null`。 。 。 .

### `querySelectorAll(selector, node, opt?)`

等值为 [文档.querySelectorall ()](https://developer.mozilla.org/docs/Web/API/Document/querySelectorAll), (中文(简体) ), [文档断面.querySelectorall ()](https://developer.mozilla.org/docs/Web/API/DocumentFragment/querySelectorAll) 财务报告和审定财务报表 [元素. query 选择器全部( )](https://developer.mozilla.org/docs/Web/API/Element/querySelectorAll)。 。 。 . **页:1**: 返回标准 `Array<Element>`,而不是一个 `NodeList`。 。 。 .

-   `selector` **{\\fn黑体\\fs22\\bord1\\shad0\\3ahbe\\4ah00\\fscx67\\fscy66\\2chffffff\\3ch808080}你来干什么** CSS选取器.
-   `node` **{文档{文档{文档碎片}{元素}** 节点可以在里面找到.
-   `opt` **{对象}?** 选项 :
    -   `opt.noexcept` **怎么样?** `true` 以压制例外并返回空数组 `[]` 换句话说.
    -   `opt.warn` **怎么样?** `true` 当遇到不支持或贬值的特性时,向控制台输出警告.
-   **回返** **{箭头}** 匹配元素组合 .

### `check(selector, node, opt?)`

检查元素是否匹配 CSS 选择器并返回额外的抽象语法树信息 . **页:1**:选择器中的任何伪元素都被排除在匹配评价之外.

-   `selector` **{\\fn黑体\\fs22\\bord1\\shad0\\3ahbe\\4ah00\\fscx67\\fscy66\\2chffffff\\3ch808080}你来干什么** CSS选取器.
-   `node` **{元素}** 元素节点.
-   `opt` **{对象}?** 选项 :
    -   `opt.requireAst` **怎么样?** 表示是否总是尝试分析并返回 AST .
    -   `opt.noexcept` **怎么样?** `true` 来压制例外,并将错误保存在 `error` 而不是丢弃.
    -   `opt.warn` **怎么样?** `true` 当遇到不支持或贬值的特性时,向控制台输出警告.
-   **回返** **{检查结果}** 含有下列属性的对象:
    -   `match` **{布尔}** `true` 如果元素与选择器匹配, `false` 否则.
    -   `pseudoElement` **{字符串} 无效}** 从选择器提取的伪元素,如果有的话.
    -   `ast` **{对象}{无效}** 解析的 AST 对象 .
    -   `error` **{DOM Excuseion } 错误 {{} 无效}** 错误对象, 如果有的话 .

### `extractSubjects(selector, caseSensitive?)`

分析一个选择器并提取最右侧的主题密钥( Id, Class, Tag) .

-   `selector` **{\\fn黑体\\fs22\\bord1\\shad0\\3ahbe\\4ah00\\fscx67\\fscy66\\2chffffff\\3ch808080}你来干什么** CSS选取器.
-   `caseSensitive` **怎么样?** `true` 如果标记键对大小写敏感。 默认为 `false`。 。 。 .
-   **回返** **{箭头}** 一系列取出的主题密钥 。 每个对象包含:
    -   `id` **{字符串} 无效}** 身份证.
    -   `className` **{字符串} 无效}** 阶级名相.
    -   `tag` **{字符串} 无效}** 标签名称.

### `supports(selector)`

检查给定的 CSS 选择器是否由此引擎支持 . 支持的选取者完整名单见下表.

-   `selector` **{\\fn黑体\\fs22\\bord1\\shad0\\3ahbe\\4ah00\\fscx67\\fscy66\\2chffffff\\3ch808080}你来干什么** CSS选取器.
-   **回返** **{布尔}** `true` 如果选择器被支持, `false` 否则.

### `clear(clearAll?)`

清除内部缓存以释放内存.

-   `clearAll` **怎么样?** 是否清除所有缓存 。 如果错误, 只有缓存匹配结果被清除 。 默认为 `false`。 。 。 .
-   **回返** **{**

## 支持的 CSS 选择器

| 图案 | 支助 | 说明 |
| :-- | :-: | :-- |
| `*` | ✓ |  |
| `E` | ✓ |  |
| `ns|E` | ✓ |  |
| `*|E` | ✓ |  |
| `|E` | ✓ |  |
| `E F` | ✓ |  |
| `E > F` | ✓ |  |
| `E + F` | ✓ |  |
| `E ~ F` | ✓ |  |
| `F || E` | 不支持 |  |
| `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:defined` | 部分获得支持 | 尚未支持与 MathML 匹配 . |
| `E:dir(ltr)` | ✓ |  |
| `E:lang(en)` | ✓ |  |
| `E:any-link` | ✓ |  |
| `E:link` | ✓ |  |
| `E:visited` | ✓ | 回返 `false` 或者说 `null` 防止指纹. |
| `E:local-link` | ✓ |  |
| `E:target` | ✓ |  |
| `E:target-within` |  | 已删除. |
| `E:scope` | ✓ |  |
| `E:hover` | ✓ |  |
| `E:active` | ✓ |  |
| `E:focus` | ✓ |  |
| `E:focus-visible` | ✓ |  |
| `E:focus-within` | ✓ |  |
| `E:current` | 不支持 |  |
| `E:current(s)` | 不支持 |  |
| `E:past` | 不支持 |  |
| `E:future` | 不支持 |  |
| `E:open` | 部分获得支持 | 与 `<select>`,比如说. `select:open`,或 `<input type="color">` 不支持. |
| `E:popover-open` | 不支持 |  |
| `E:enabled`  
`E:disabled` | ✓ |  |
| `E:read-write`  
`E:read-only` | ✓ |  |
| `E:placeholder-shown` | ✓ |  |
| `E:default` | ✓ |  |
| `E:checked` | ✓ |  |
| `E:indeterminate` | ✓ |  |
| `E:blank` | 不支持 |  |
| `E:valid`  
`E:invalid` | ✓ |  |
| `E:in-range`  
`E:out-of-range` | ✓ |  |
| `E:required`  
`E:optional` | ✓ |  |
| `E:user-valid`  
`E:user-invalid` | 不支持 |  |
| `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)` | 不支持 |  |
| `E:nth-last-col(n)` | 不支持 |  |
| `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, ...)` | ✓ |  |
| `&` | ✓ | 只支持最外侧 `&`,即相当于 `:scope` |

\*1 : (中文(简体) ) `ElementInternals.states`,也就是说. `CustomStateSet`,在jsdom中未执行,所以您需要在自定义元素构建器中应用补丁.

```javascript
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;
  }
}
```

## 业绩

见 [基准](https://github.com/asamuzaK/domSelector/actions/workflows/benchmark.yml) 最新结果.

## 承认

以下资源对于DOM选择器的开发有很大帮助.

-   [CSSTree (英语)](https://github.com/csstree/csstree)
-   [红酒](https://github.com/danburzo/selery)
-   [日记](https://github.com/jsdom/jsdom)
-   [nwsapi (英语)](https://github.com/dperini/nwsapi)

* * *

版权(c) 2023 [阿萨穆扎克(卡兹)](https://github.com/asamuzaK/)

## 常见问题

### @asamuzakjp/dom-selector 是什么？

CSS选择器引擎\.

### 如何安装 @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 和提交记录判断。

