0

This my code but there is an error if you override the highlighted text.
The error is:

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

JS

function surroundSelection() { var span = document.createElement("span"); span.setAttribute('class', 'hlt') if (window.getSelection) { var sel = window.getSelection(); if (sel.rangeCount) { var range = sel.getRangeAt(0).cloneRange(); range.surroundContents(span); sel.removeAllRanges(); sel.addRange(range); } } } 
3
  • 1
    What have you tried to deal with the problem? The error is fairly clear: The selection includes parts of a node that isn't a text node, and so surroundContents itself can't do the job. You have to look at what's in the range and deal with how to highlight the selection cross-element. MDN even flags this up: "An exception will be thrown, however, if the Range splits a non-Text node with only one of its boundary points." So you'll need more than one span in that case. Commented Jul 9, 2016 at 8:39
  • yes i dont have idea on how how it can pass to element and override the highlight. yes i need more span element for that. hopefully someone can help me. Commented Jul 9, 2016 at 9:02
  • Working through it yourself will be the best help. Otherwise, this is just a "please write this for me" request, not a question. Commented Jul 9, 2016 at 9:04

1 Answer 1

1

Try this instead:

function surroundSelection() { var selection= window.getSelection().getRangeAt(0); var selectedText = selection.extractContents(); var span= document.createElement("span"); span.setAttribute('class', 'hlt') span.appendChild(selectedText); selection.insertNode(span); } 
Sign up to request clarification or add additional context in comments.

1 Comment

it's correct. but when we have multi paragraph this is not work correctly.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.