Text.splitText() - Web APIs 编辑

The Text.splitText() method breaks the Text node into two nodes at the specified offset, keeping both nodes in the tree as siblings.

After the split, the current node contains all the content up to the specified offset point, and a newly created node of the same type contains the remaining text. The newly created node is returned to the caller. If the original node had a parent, the new node is inserted as the next sibling of the original node. If the offset is equal to the length of the original node, the newly created node has no data.

Separated text nodes can be concatenated using the Node.normalize() method.

Syntax

newNode = textNode.splitText(offset)

Parameters

offset
The index immediately before which to break the text node.

Return value

Returns a newly created Text node that contains the text after the specified offset point.

Exceptions thrown

A DOMException with a value of INDEX_SIZE_ERR is thrown if the specified offset is negative or is greater than the number of 16-bit units in the node's text; a DOMException with a value of NO_MODIFICATION_ALLOWED_ERR is thrown if the node is read-only.

Example

In this example, the text of a <p> is split into two text nodes, and a <u> is inserted between them.

HTML

<p>foobar</p>

JavaScript

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>

Result

Specifications

SpecificationStatusComment
DOM
The definition of 'Text.splitText' in that specification.
Living StandardNo change from Document Object Model (DOM) Level 3 Core Specification.
Document Object Model (DOM) Level 3 Core Specification
The definition of 'Text.splitText' in that specification.
ObsoleteNo change from Document Object Model (DOM) Level 2 Core Specification.
Document Object Model (DOM) Level 2 Core Specification
The definition of 'Text.splitText' in that specification.
ObsoleteNo change from Document Object Model (DOM) Level 1 Specification.
Document Object Model (DOM) Level 1 Specification
The definition of 'Text.splitText' in that specification.
ObsoleteInitial definition.

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:43 次

字数:6370

最后编辑:7年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文