Merging Text Nodes Together After Inserting Span

后端 未结 4 1499
离开以前
离开以前 2020-12-14 01:08

I have an extension where I am storing/retrieving a section of the DOM structure (always a selection of text on the screen) the user has selected. When I am storing a select

4条回答
  •  醉酒成梦
    2020-12-14 01:40

    Use element.normalize().

    After you remove the span you inserted, you can use the element.normalize() method to merge the extra text nodes that were created as a result of the insertion/removal of the span. The normalize() method puts the specified element and all of its subtree into a "normalized" form (i.e. no text nodes in the subtree are empty and there are no adjacent text nodes). Found, thanks to @tcovo's comment.

    Text nodes inside of an element are broken apart if you insert nodes and then remove them. Unfortunately they don't automatically re-merge once the extra node is removed. To answer peoples' questions as to "why" this matters, it usually causes issues when working with text highlighting in your UI.

提交回复
热议问题