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

Pietro Di Bello P.DiBello at quinary.com
Fri Aug 29 03:17:15 CDT 2003

Hi all, 

I read this thread by Simon Willison, it was posted one year ago...And, since I have the same problem, I was wandering if anyone has been able to handle this issue in the meanwhile...

Thanks a lot,


At 15:35 24/05/02 +0100, I wrote:
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.

Looks like I spoke too soon. I've just discovered that the object returned
by document.getSelection() in Mozilla is a "Selection" object which can be
further manipulated. Documentation on this page:


My problem now is that if I select some text in a text box and then click
on a button outside the text box in Mozilla the text is unselected (due to
my selection of the button). This is preventing me from running the code to
process the selection as the act of hitting the button cancels the
selection I want to use :(

The code I am playing with at the moment is as follows:

<script type="text/javascript">
function doit() {
   theSelection = document.getSelection();
   if (!theSelection)
     return false;
<textarea rows=5 cols=40></textarea>
<input type="button" onClick="doit()" value="hi" />

<tip type="Client side code testing" author="Simon Willison">
If you want to do a quick experiment with HTML, CSS or JavaScript without
having to create a whole new HTML document head over to www.w3schools.com
and use their "Try it" feature - this provides you with a textarea to enter
HTML on the right and a frame where the code you have entered will be
displayed on the right. It's a great tool for trying things in a hurry.
Direct link:


More information about the thelist mailing list