InvalidStateError: Failed to execute 'surroundContents' on 'Range': The Range has partially selected a non-Text node

Viewed 1247

Good day, I am trying to make a reader where user can highlight text by multiple color,I have written code on sandbox link is below.

https://codesandbox.io/s/gallant-snowflake-oxko7?file=/src/App.js

everything is working fine but when I am trying change previously highlighted color by selecting selected text I am getting this error .

InvalidStateError: Failed to execute 'surroundContents' on 'Range': The Range has partially selected a non-Text node. enter image description here

1 Answers

I have found some Solution and fixed it by it. Link below

changed code from

let span = document.createElement("span");

    t = document.all
      ? document.selection.createRange().text
      : document.getSelection();
    setXaxis(e.clientX / 2);
    setYaxis(e.clientY / 2);

    console.log(e.clientX);
    console.log(e.clientY);
    // let text =  document.querySelector(".App").innerText;
    //document.querySelector(".App").html(text.replace(t, spn));
    //document.getElementById('result').innerText = t;
    //alert(t.rangeCount);
    span.style.backgroundColor = color;
    let range = t.getRangeAt(0).cloneRange();
    range.surroundContents(span);
    t.removeAllRanges();
    t.addRange(range);

to

 var range = window.getSelection().getRangeAt(0);
let span = document.createElement("span");

span.style.backgroundColor = color;
span.appendChild(range.extractContents());
range.insertNode(span);

https://codesandbox.io/s/optimistic-https-zlfpe?file=/src/App.js

Related