Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add tags around selected text in an element

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.

like image 355
EmilyNeedsToCode Avatar asked Jul 11 '14 04:07

EmilyNeedsToCode


People also ask

How do you tag an element in HTML?

An HTML element is defined by a starting tag. If the element contains other content, it ends with a closing tag. For example, <p> is starting tag of a paragraph and </p> is closing tag of the same paragraph but <p>This is paragraph</p> is a paragraph element.


2 Answers

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.

like image 174
Edisonator Avatar answered Sep 24 '22 02:09

Edisonator


You can simply do like this.

$('body').mouseup(function(){
   var span = document.createElement("span");
    if (window.getSelection) {
        var sel = window.getSelection();
        if (sel.rangeCount) {
            var range = sel.getRangeAt(0).cloneRange();
            range.surroundContents(span);
            sel.removeAllRanges();
            sel.addRange(range);
        }
    }
});

Fiddle

Reference Wrapping a selected text node with span

like image 34
Anoop Joshi P Avatar answered Sep 25 '22 02:09

Anoop Joshi P