How to extract selected text from inside multiple nested spans to plain text while preserving the spans

24 views Asked by At

I'm trying to make an inline tool for EditorJS that will clear any formatting on the selected text applied via spans. The issue I'm having is that the tool should clear the formatting only on the selected text which may be nested in multiple overlapping spans, with multiple overlaying formats, which all need to be preserved. In essence I need to extract the text "out" of the nested spans. I can't change the format of the spans but there are only spans in the text and it is all nested in a single div.

For example

Test<span class="format-bold">of a</span><span style="color: #FEBE10;" class="format-color"><span class="format-bold">randomly </span>formatted</span><span class="format-italic">text </span>here.

when selecting the text "a random" and pressing the clear button, the resulting snippet should be

Test<span class="format-bold">of </span>a random<span style="color: #FEBE10;" class="format-color"><span class="format-bold">ly </span>formatted</span><span class="format-italic">text </span>here.

The issues I'm getting with various approaches are that it either doesn't work for non-contiguously arbitrarily nested spans or when the selection overlaps a start or end tag without the other.

I've tried using the Rangy library as well as various other approaches to detect the start and end containers of the selection and try to recursively check for parents and keep unwrapping the text but no approach I tried worked.

What would be the best way to handle this, if any? Thank you for any help.

0

There are 0 answers