Text: splitText() 方法
Text 接口的 splitText() 方法会在指定偏移量处将一个 Text 节点拆分成两个节点,并将这两个节点都保留在树中作为兄弟节点。
拆分后,当前节点将包含指定偏移量之前的所有内容,一个同类型的新创建的节点将包含剩余的文本。新创建的节点将返回给调用者。如果原始节点有父节点,新节点将作为原始节点的下一个兄弟节点插入。如果偏移量等于原始节点的长度,则新创建的节点将不包含任何数据。
可以通过 Node.normalize() 方法将分开的文本节点连接起来。
语法
js
splitText(offset)
参数
offset-
要拆分文本节点的索引,在该索引之前进行拆分。
返回值
返回新创建的 Text 节点,该节点包含指定偏移量之后的内容。
异常
IndexSizeErrorDOMException-
如果指定的偏移量为负数,或者大于节点文本中的 16 位单元的数量,则抛出此异常。
NoModificationAllowedErrorDOMException-
如果节点是只读的,则抛出此异常。
示例
在此示例中,一个 <p> 元素的文本被拆分成两个文本节点,并在它们之间插入了一个 <u> 元素。
html
<p>foobar</p>
js
const p = document.querySelector("p");
// Get contents of <p> as a text node
const foobar = p.firstChild;
// Split 'foobar' into two text nodes, 'foo' and 'bar',
// and save 'bar' as a const
const bar = foobar.splitText(3);
// Create a <u> element containing ' new content '
const u = document.createElement("u");
u.appendChild(document.createTextNode(" new content "));
// Add <u> before 'bar'
p.insertBefore(u, bar);
// The result is: <p>foo<u> new content </u>bar</p>
规范
| 规范 |
|---|
| DOM # ref-for-dom-text-splittext① |
浏览器兼容性
加载中…
另见
- 它所属的
Text接口。 - 相反的方法:
Node.normalize。