Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

javascript - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...