Add tags around selected text in an element

javascript, jquery

Solution

I have a solution. Get the `Range` of the selecion and deleteContent of it, then insert a new `span` in it .

$('body').mouseup(function(){
    var selection = getSelectedText();
    var selection_text = selection.toString();

    // How do I add a span around the selected text?

    var span = document.createElement('SPAN');
    span.textContent = selection_text;

    var range = selection.getRangeAt(0);
    range.deleteContents();
    range.insertNode(span);
});

You can see the DEMO here

UPDATE

Absolutly, the selection will be delete at the same time. So you can add the selection range with js code if you want.

Problem

How can I add `<span>` tags around selected text within an element? For example, if somebody highlights "John", I would like to add span tags around it. HTML ``` <p>My name is Jimmy John, and I hate sandwiches. My name is still Jimmy John.</p> ``` JS ``` function getSelectedText() { t = (document.all) ? document.selection.createRange().text : document.getSelection(); return t; } $('p').mouseup(function(){ var selection = getSelectedText(); var selection_text = selection.toString(); console.log(selection); console.log(selection_text); // How do I add a span around the selected text? }); ``` http://jsfiddle.net/2w35p/ There is a identical question here: jQuery select text and add span to it in an paragraph, but it uses outdated jquery methods (e.g. live), and the accepted answer has a bug.

Original source

Related problems