Break Node Groups in Selected Text into Separated Nodes

I’m trying to surround selected text which are contained in multiple text nodes with span tags using the surroundContents method of a range object but it only works if the selection is completely contained within a single text node. So I thought about breaking up the range into multiple ranges at the locations where two HTML elements meet, use the surroundContents to surround the text I want, then combine the ranges together into a single range.

The problems I’m facing are I don’t know how to breakup the range and make sure the breaks take place at the right locations. Not only that but aside from Firefox I don’t think Chrome and other browsers support combining multiple ranges into a single range. If anyone has done this before please point me in the right direction, thanks.

Hi @liagapi555, maybe you could just create new ranges by the common parents of the selected nodes; then surround these ranges individually, and set the selection to these new ranges. I’ve been playing around a bit on this rainy Saturday and came up with the following:

2 Likes

Nice bit of code there m3g4p0p, will be picking the bones out of that :smiley:

Apart from interesting things like the use of symbol.iterator, tree walkers, reducing with maps, I’m interested to know where you get your information on the dom from — surely not just MDN

BITD there used to be books entirely devoted to the subject, but the last one I can think of was 2013 Dom Enlightenment. Even the latest Definitive Guide skims over the topic.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.