Javascript Select Range
Highlights selected text.
by jme11
HTML
<h3>hello world! hello world! hello world</h3>
<div>hello world! hello world hello world!</div><span>hello world! hello world</span>
CSS
.red{color:red;}
JavaScript
$(document).on("mouseup", function (e) {
var selected = getSelection();
var range = selected.getRangeAt(0);
console.log(range);
if(selected.toString().length > 1){
var newNode = document.createElement("span");
newNode.setAttribute("class", "red");
range.surroundContents(newNode);
}
selected.removeAllRanges();
});
function getSelection() {
var seltxt = '';
if (window.getSelection) {
seltxt = window.getSelection();
} else if (document.getSelection) {
seltxt = document.getSelection();
} else if (document.selection) {
seltxt = document.selection.createRange().text;
}
else return;
return seltxt;
}