CancelImage Upload

Inserting bold, italic and underline tags around highlighted text inside a textarea

To insert bold, italic, underline or any other HTML tags into a selected range within a textarea we need to first of all establish what area has been highlighted. In JavaScript we can access this property through the following path:


Through the above code we have loaded an object that can deliver a range of information, including the text that has been highlighted:


As the following example shows we can use this path to first of all identify what part of the textarea has been highlighted, load the areas text, and then surround the text with the specified tags passed to the function within the highlighted area:

<script type="text/javascript" language="javascript">
function addTag(tag)

         var textrange = document.selection.createRange();

         var string = textrange.text;


         textrange.text = "<" + tag + ">" + string + "</" + tag + ">";


<form name="form1"method="post">

<textarea style="width:300px; height:300px;" name="field1">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi.</textarea><br>

<input type="button" onclick="javascript:addTag('b');" value="Bold">

<input type="button" onclick="javascript:addTag('i');" value="Italic">

<input type="button" onclick="javascript:addTag('u');" value="Underline">



Want to leave a comment?

No problem. Just enter your email and password below.

register | home | reminder

myDesignTool Networking •