James Perez Dy
James Perez Dy

Reputation: 11

Wrap the highlight text with span element in JQuery or JavaScript

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);
    }
  }
}     

Upvotes: 0

Views: 995

Answers (1)

jazzcat
jazzcat

Reputation: 4441

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);
}

Upvotes: 1

Related Questions