Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery select text and add span to it in an paragraph

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.

like image 417
Mircea Avatar asked Feb 10 '10 13:02

Mircea


1 Answers

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));
like image 166
Mathias Bynens Avatar answered Sep 20 '22 00:09

Mathias Bynens