简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM