Javascript: return selection (selected text) after DOM manipulation

This function returns the 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 calling the function, the selection (selected text) is deleted. How to return this choice, or maybe, how can I name a function without losing my choice in the first place?

+3
source share
1 answer

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 a few questions you need to know:

  • Range surroundContents() : DOM, Range node. , surroundContents() , , , . . DOM Level 2 Range spec .
  • IE 8 DOM Range Selection . IE 9 , .
  • , , rangeCount, , .
+6

Source: https://habr.com/ru/post/1781002/


All Articles