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。