0

I'd like to take the selected text on screen (text highlighted with the mouse) and when a button is pushed wrap that text in a tag. I'd like to use jquery but if it can be done in another framework that would be fine too.

I haven't been able to figure out how to do this yet, so any thoughts are appreciated. Also I know you can run into issues if the text goes across several elements so for now case just assume the text highlighted is all contained in a

tag.

Thanks!

vrish88
  • 20,047
  • 8
  • 38
  • 56

2 Answers2

0

Here is a post on working with selected text. The getSelection() method can be used to get the selected text, then you should be able to replace that text with text wrapped in a tag.

Dave Swersky
  • 34,502
  • 9
  • 78
  • 118
0

Highlighting the selected text doesn't necessarily require you to wrap it. In fact, trying to wrap it is difficult if the range of the selection spans multiple tags (i.e. doesn't surround nicely closed tags).

Here's an answer that highlights the current selection without wrapping it: Javascript Highlight Selected Range Button.

He uses execCommand to let the browser highlight the current document selection for you. Pretty sweet.

Community
  • 1
  • 1
Crescent Fresh
  • 115,249
  • 25
  • 154
  • 140
  • awesome thanks... I figured there was someone else out there who had already asked this question. As a result I've voted to close this question and have it point to the one you mentioned. – vrish88 Dec 07 '09 at 19:05