I have a function that gets the selected text, the text is selected by mouse, and add it into a variable. I want to add tags around that variable in the selected text – in that paragraph.
$("p").live("mouseup",function() {
selection = getSelectedText();
if(selection.length >= 3) {
var $spn = $("<span></span>").html(selection).addClass("selected");
$("p").wrap($spn);
}
});
//Grab selected text
function getSelectedText(){
if(window.getSelection){
return window.getSelection().toString();
}
else if(document.getSelection){
return document.getSelection();
}
else if(document.selection){
return document.selection.createRange().text;
}
}
I can get the text selection variable but instead of placing the <span></span> around the selected text from the paragraph <p>, my function wraps this outside.
How can I replace it in the paragraph?
Thank you.
This is where it goes wrong:
This means you’re wrapping the
spanaround the paragraph.I think you mean to do something like this: