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?
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:
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.Selection object to other browsers. IE 9 will have similar Range and Selection capabilities as other browsers.rangeCount property before proceeding, otherwise you'll get exception if there is no selection.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With