Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: return selection(highlighted text) after DOM manipulation

This function returns text that the user has selected and wraps it in tags, in this case bold tags.

function makeBold() {
    var selection = window.getSelection();
    var range = selection.getRangeAt(0);
    var newNode = document.createElement("b");
    range.surroundContents(newNode);
}



Now after I call the function, the selection (highlighted text) is removed. How do I return that selection or maybe how do I call the function without losing my selection in the first place?

like image 873
Zebra Avatar asked Dec 31 '25 01:12

Zebra


1 Answers

The following will work:

function makeBold() {
    var selection = window.getSelection();
    if (selection.rangeCount) {
        var range = selection.getRangeAt(0).cloneRange();
        var newNode = document.createElement("b");
        range.surroundContents(newNode);
        selection.removeAllRanges();
        selection.addRange(range);
    }
}

However, there are several issues to be aware of:

  • Range's surroundContents() method will not work for every Range: it has to make sense within the DOM to surround the Range contents within a new node. For example, using surroundContents() on a Range that spans two paragraphs but doesn't fully select either will throw an error. See the DOM Level 2 Range spec for the formal definition of this.
  • IE up to and including version 8 doesn't support DOM Range, and has a totally different Selection object to other browsers. IE 9 will have similar Range and Selection capabilities as other browsers.
  • You need to check the selection's rangeCount property before proceeding, otherwise you'll get exception if there is no selection.
like image 55
Tim Down Avatar answered Jan 02 '26 15:01

Tim Down



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!