[thelist] Using Javascript to add tags to selected text in textarea

Simon Willison simon at incutio.com
Fri May 24 09:36:42 CDT 2002

At 14:11 23/05/02 -0400, you wrote:
>Hi Simon-
>I don't know that you'll be able to do this with Mozilla, but it is
>certainly possible with IE.  Check this out:
>theSelection = document.selection.createRange().text;
>document.selection.createRange().text = "*" + theSelection + "*";
>This is straight off the phpBB forum software, at phpBB.com.  HTH!

Thanks, that works a treat in IE - in fact I've expanded it slightly to
make sure it only works inside text areas (the basic code will add tags to
text selected anywhere on the page):

<script type="text/javascript">
function addStarsToSelection() {
   theSelection = document.selection.createRange().text;
   if (!theSelection)
     return false;
   if (document.selection.createRange().parentElement().tagName != 'TEXTAREA')
     return false;
   document.selection.createRange().text = "*" + theSelection + "*";

I think I'll have to give up on the Mozilla implementation. It seems that
Mozilla has a document.getSelection() method which can grab the selected
text but there is no equivalent to Microsoft's textrange object through
which you can manipulate the currently selected area.

Thanks for the help,

Simon Willison

More information about the thelist mailing list