Search code examples
javascripttextselectiongetselection

Selected text remove element already wrapped in a span


I have a scenario/dilemma, I am a little stuck trying to figure out. Below will be my best of a visual representation.

1. I select

This is dummy text to select

2. I bold and it gets wrapped with a span

This is dummy text to select

<h2 This is dummy <span style="font-weight: 700;">text to select</span></h2>

3. Now lets say I want to select some text but we know it's already wrapped in a span

This is dummy [BOLD]text[BOLD] to select

4. Its a crossover with selected text, so now my code. In my important comment, I can identify that the element is found in the selection. But how can I find it and then remove the span.

const el = document.createElement('span');

  function handleNodeWrap(){
    if(selection?.containsNode(el,true)){
      //! IMPORTANT find and remove element of selected text
    }
    surroundSelection(el);
  }

Solution

  • Here's one approach to remove the span from the selected text:

    const el = document.createElement('span');
    
    function handleNodeWrap() {
      if (selection?.containsNode(el, true)) {
        // find parent node of the selected text
        let parentNode = selection.anchorNode.parentNode;
        // create a new range that selects the entire content of the parent node
        let range = document.createRange();
        range.selectNodeContents(parentNode);
        // replace the content of the parent node with the plain text version
        let text = range.extractContents().textContent;
        parentNode.textContent = text;
      } else {
        surroundSelection(el);
      }
    }