---
title: "节点位置"
description: "了解 Tiptap 中的节点位置，以便进行文档导航和操作。请在文档中了解更多信息！"
canonical_url: "https://tiptap.zhcndoc.com/editor/api/node-positions"
---

# 节点位置

了解 Tiptap 中的节点位置，以便进行文档导航和操作。请在文档中了解更多信息！

节点位置（`NodePos`）描述了节点及其子节点和父节点的具体位置，提供了它们之间的便捷导航。节点位置深受 DOM 的启发，基于 ProseMirror 的 [ResolvedPos](https://prosemirror.net/docs/ref/#model.ResolvedPos) 实现。

## 使用节点位置

创建新的节点位置的最简单方法是使用编辑器实例中的辅助函数。通过这种方式，您始终使用正确的编辑器实例，并可以直接访问 API。

```js
// 在这里设置您的编辑器

// 最外层文档节点的 NodePosition
const $doc = editor.$doc

// 获取文档中所有类型为 'heading' 的节点
const $headings = editor.$nodes('heading')

// 根据属性进行筛选
const $h1 = editor.$nodes('heading', { level: 1 })

// 直接选择节点
const $firstHeading = editor.$node('heading', { level: 1 })

// 当类型未知时，通过 $pos 方法创建新的 NodePos
const $myCustomPos = editor.$pos(30)
```

您还可以创建自己的 NodePos 实例：

```js
// 您需要有一个编辑器实例
// 和一个您想映射到的位置
const myNodePos = new NodePos(100, editor)
```

## 我可以用 NodePos 做什么？

`NodePos` 让您可以类似于浏览器中的文档 DOM 遍历文档。您可以访问父节点、子节点和兄弟节点。

**示例：** 获取并更新 `codeBlock` 节点的内容

```js
// 从文档中获取第一个 codeBlock
const $codeBlock = editor.$node('codeBlock')

// 获取 codeBlock 节点的前一个 NodePos
const $previousItem = $codeBlock.before

// 轻松更新内容
$previousItem.content = '<p>更新后的内容</p>'
```

如果您熟悉 DOM，则此示例会显得很熟悉：

**示例：** 选择列表项并在项目符号列表中插入新项

```js
// 从文档中获取一个项目符号列表
const $bulletList = editor.$node('bulletList')

// 获取所有项目符号列表中的 listItems
const $listItems = $bulletList.querySelectorAll('listItem')

// 获取最后一个 listItem
const $lastListItem = $listItems[0]

// 在最后一个之后插入一个新 listItem
editor.commands.insertContentAt($lastListItem.after, '<li>新项</li>')
```

## API

### NodePos

NodePos 类是您将要操作的主要类。它描述了节点、它的子节点、它的父节点的具体位置以及在它们之间便捷导航的方式。它们深受 DOM 的启发，并基于 ProseMirror 的 [ResolvedPos](https://prosemirror.net/docs/ref/#model.ResolvedPos) 实现。

#### 方法

| 方法                 | 参数                               | 返回值                | 描述                                             |
| ------------------ | -------------------------------- | ------------------ | ---------------------------------------------- |
| `constructor`      | `pos`（数字），`editor`（对象）           | `NodePos`          | 在指定的 `editor` 实例中创建给定位置（`pos`）的新的 `NodePos` 实例 |
| `closest`          | `nodeType`（字符串）                  | `NodePos` 或 `null` | 在文档结构中向上查找最近匹配的 `NodePos`。如果未找到匹配项，则返回 `null`  |
| `querySelector`    | `nodeType`（字符串），`attributes`（对象） | `NodePos` 或 `null` | 在文档结构中向下查找第一个匹配的 `NodePos`。可以通过属性进行过滤          |
| `querySelectorAll` | `nodeType`（字符串），`attributes`（对象） | `Array<NodePos>`   | 在文档结构中向下查找所有匹配的 `NodePos` 实例。可以通过属性进行过滤        |
| `setAttribute`     | `attributes`（对象）                 | `NodePos`          | 在当前 `NodePos` 上设置指定的属性                         |

##### constructor

**参数**

- `pos` – 您想映射到的位置
- `editor` – 您想使用的编辑器实例

**返回值** `NodePos`

```js
const myNodePos = new NodePos(100, editor)
```

##### closest

您节点位置向上深度的最近 NodePos 实例。如果没有匹配的 NodePos，将返回 `null`。

**返回值** `NodePos | null`

```js
const closest = myNodePos.closest('bulletList')
```

##### querySelector

您节点位置向下深度的第一个匹配 NodePos 实例。如果没有匹配的 NodePos，将返回 `null`。

您还可以通过第二个参数进行属性过滤。

**返回值** `NodePos | null`

```js
const firstHeading = myNodePos.querySelector('heading')
const firstH1 = myNodePos.querySelector('heading', { level: 1 })
```

##### querySelectorAll

您节点位置向下深度的所有匹配 NodePos 实例。如果没有匹配的 NodePos，将返回一个空数组。

您还可以通过第二个参数进行属性过滤。

**返回值** `Array<NodePos>`

```js
const headings = myNodePos.querySelectorAll('heading')
const h1s = myNodePos.querySelectorAll('heading', { level: 1 })
```

##### setAttribute

在当前 NodePos 上设置属性。

**返回值** `NodePos`

```js
myNodePos.setAttribute({ level: 1 })
```

#### 属性

| 属性            | 类型                       | 描述                                   |
| ------------- | ------------------------ | ------------------------------------ |
| `node`        | `Node`（ProseMirror Node） | 当前 `NodePos` 的 ProseMirror 节点        |
| `parent`      | `NodePos`                | 当前 `NodePos` 的父节点                    |
| `children`    | `Array<NodePos>`         | 当前 `NodePos` 的子节点                    |
| `firstChild`  | `NodePos` 或 `null`       | 当前 `NodePos` 的第一个子节点，如果没有则返回 `null`  |
| `lastChild`   | `NodePos` 或 `null`       | 当前 `NodePos` 的最后一个子节点，如果没有则返回 `null` |
| `pos`         | `number`                 | 文档中节点的位置                             |
| `from`        | `number`                 | 节点的起始位置                              |
| `to`          | `number`                 | 节点的结束位置                              |
| `range`       | `number`                 | 当前 `NodePos` 的节点范围（从–到）              |
| `content`     | `string`                 | 当前 `NodePos` 的节点内容。您可以设置此内容来更新节点的内容  |
| `attributes`  | `Object`                 | 当前 `NodePos` 的节点属性                   |
| `textContent` | `string`                 | 当前 `NodePos` 的节点文本内容                 |
| `depth`       | `number`                 | 节点在文档结构中的深度（级别）                      |
| `size`        | `number`                 | 当前 `NodePos` 的节点大小                   |
| `before`      | `NodePos` 或 `null`       | 当前 `NodePos` 之前的节点，如果没有节点则返回 `null`  |
| `after`       | `NodePos` 或 `null`       | 当前 `NodePos` 之后的节点，如果没有节点则返回 `null`  |

##### node

当前节点位置的 ProseMirror 节点。

**返回值** `Node`

```js
const node = myNodePos.node
node.type.name // 'paragraph'
```

##### element

当前节点位置的 DOM 元素。

**返回值** `Element`

```js
const element = myNodePos.element
element.tagName // 'P'
```

##### content

您节点位置的内容。您可以设置此内容的新值以更新节点的内容。

**返回值** `string`

```js
const content = myNodePos.content
myNodePos.content = '<p>更新后的内容</p>'
```

##### attributes

您节点位置的属性。

**返回值** `Object`

```js
const attributes = myNodePos.attributes
attributes.level // 1
```

##### textContent

您节点位置的文本内容。

**返回值** `string`

```js
const textContent = myNodePos.textContent
```

##### depth

您节点位置的深度。

**返回值** `number`

```js
const depth = myNodePos.depth
```

##### pos

您节点位置的位置。

**返回值** `number`

```js
const pos = myNodePos.pos
```

##### size

您节点位置的大小。

**返回值** `number`

```js
const size = myNodePos.size
```

##### from

您节点位置的 from 位置。

**返回值** `number`

```js
const from = myNodePos.from
```

##### to

您节点位置的 to 位置。

**返回值** `number`

```js
const to = myNodePos.to
```

##### range

您节点位置的范围。

**返回值** `number`

```js
const range = myNodePos.range
```

##### parent

您节点位置的父 NodePos。

**返回值** `NodePos`

```js
const parent = myNodePos.parent
```

##### before

您节点位置之前的 NodePos。如果没有 NodePos 之前，将返回 `null`。

**返回值** `NodePos | null`

```js
const before = myNodePos.before
```

##### after

您节点位置之后的 NodePos。如果没有 NodePos 之后，将返回 `null`。

**返回值** `NodePos | null`

```js
const after = myNodePos.after
```

##### children

您节点位置的子 NodePos 实例。

**返回值** `Array<NodePos>`

```js
const children = myNodePos.children
```

##### firstChild

您节点位置的第一个子 NodePos 实例。如果没有子节点，将返回 `null`。

**返回值** `NodePos | null`

```js
const firstChild = myNodePos.firstChild
```

##### lastChild

您节点位置的最后一个子 NodePos 实例。如果没有子节点，将返回 `null`。

**返回值** `NodePos | null`

```js
const lastChild = myNodePos.lastChild
```
