jQuery select text and add span to it in an paragraph

jquery, select, text

Solution

This is where it goes wrong:

var $spn = $("<span></span>").html(selection).addClass("selected");
$("p").wrap($spn);

This means you’re wrapping the `span` around the paragraph.

I think you mean to do something like this:

var spn = '<span class="selected">' + selection + '</span>';
$(this).html($(this).html().replace(selection, spn));

Problem

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.

Original source