Text.splitText()
method breaks the
文本
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()
方法。
newNode = textNode.splitText(offset)
offset
The index immediately before which to break the text node.
返回新近创建的
文本
node that contains the text after the specified offset point.
A
DOMException
采用值
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
采用值
NO_MODIFICATION_ALLOWED_ERR
is thrown if the node is read-only.
In this example, the text of a
<p>
is split into two text nodes, and a
<u>
is inserted between them.
<p>foobar</p>
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>
| 桌面 | 移动 | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
splitText
|
Chrome
1
|
Edge 12 | Firefox 1 | IE Yes |
Opera
Yes
|
Safari
Yes
|
WebView Android
Yes
|
Chrome Android
18
|
Firefox Android 4 |
Opera Android
Yes
|
Safari iOS
Yes
|
Samsung Internet Android
1.0
|
完整支持
见实现注意事项。
文本
interface it belongs to.
Node.normalize
.
文本
replaceWholeText()
splitText()
AbortController
AbortSignal
AbstractRange
Attr
ByteString
CDATASection
CSSPrimitiveValue
CSSValue
CSSValueList
CharacterData
ChildNode
注释
CustomEvent
DOMConfiguration
DOMError
DOMErrorHandler
DOMException
DOMImplementation
DOMImplementationList
DOMImplementationRegistry
DOMImplementationSource
DOMLocator
DOMObject
DOMParser
DOMPoint
DOMPointInit
DOMPointReadOnly
DOMRect
DOMString
DOMTimeStamp
DOMTokenList
DOMUserData
Document
DocumentFragment
DocumentType
元素
ElementTraversal
Entity
EntityReference
事件
EventTarget
HTMLCollection
MutationObserver
节点
NodeFilter
NodeIterator
NodeList
NonDocumentTypeChildNode
ProcessingInstruction
PromiseResolver
范围
StaticRange
TextDecoder
TextEncoder
TimeRanges
TreeWalker
TypeInfo
USVString
UserDataHandler
XMLDocument