Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Wrap / Surround Highlighted Text With An Element

I want to wrap a selected text in a div container with span, is it possible?

A user will select a text and will click a button, on button click event I want to wrap that selected text with span element. I can get the selected text using window.getSelection() but how to know its exact position in DOM structure?

like image 685
coure2011 Avatar asked Jun 13 '11 09:06

coure2011


1 Answers

If the selection is completely contained within a single text node, you can do this using the surroundContents() method of the range you obtain from the selection. However, this is very brittle: it does not work if the selection cannot logically be surrounded in a single element (generally, if the range crosses node boundaries, although this is not the precise definition). To do this in the general case, you need a more complicated approach.

Also, DOM Range and window.getSelection() are not supported in IE < 9. You'll need another approach again for those browsers. You can use a library such as my own Rangy to normalize browser behaviour and you may find the class applier module useful for this question.

Simple surroundContents() example jsFiddle: http://jsfiddle.net/VRcvn/

Code:

function surroundSelection(element) {     if (window.getSelection) {         var sel = window.getSelection();         if (sel.rangeCount) {             var range = sel.getRangeAt(0).cloneRange();             range.surroundContents(element);             sel.removeAllRanges();             sel.addRange(range);         }     } } 
like image 126
Tim Down Avatar answered Sep 21 '22 08:09

Tim Down