7

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
  • The relevant code should be in the question as a snippet rather than a sandbox link that can rot over time. Thanks.
    – ggorlen
    Jul 6, 2021 at 1:09

2 Answers 2

14

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

2
  • I am still a bit skeptical as to this is a cross-browser solution; but at least I am getting somewhere now. Thank you mate... Mar 16, 2022 at 8:33
  • it works but it like nested element span inside span.... Mar 23, 2022 at 16:25
1

The error is letting you know you're doing something illegal, so you can either try to infer what was the intention and manipulate the range manually, which is possible (but not bulletproof) or you can validate the range before doing any action:

const isSafeRange = range.startContainer === range.endContainer

So if a selection is crossing different nodes, you will detect that and return.

BTW, You don't need to clone it in your scenario

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.