I have the following javascript which highlights text when I select text and click a button.
$('.highlight').on("click", function (e) {
selected = getSelection();
range = selected.getRangeAt(0);
newNode = document.createElement("span");
newNode.setAttribute("class", "highlighted");
range.surroundContents(newNode);
});
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;
}
However this creates a lot of messy span classes within my p tag. Is it possible to immediately colour the selected text without having to wrap it in a span?
Another reason for doing this is that I want to check whether selected text already has a yellow background and if so turn it transparent (perhaps toggling between two colors)