jQuery: Convert Text to Links

I had some italic text in a paragraph and I wanted to convert this text into links, all pointing to the same url. Here’s how this can be done using a single line of jQuery code.



In the example, we have a div element with class ‘cls’ and inside this div, we have some text that is italicized. We will convert all these text elements into links and point them to www.devcurry.com



Consider this sample text:



image

jQuery code

<head>
<title>Convert Text to Link - DevCurry.com</title>
<script type="text/javascript" 
src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.1.min.js">
</script>     
<script type="text/javascript">
$(function () {
  $("#btn").click(function () {
     $('div.cls i').wrap('<a href="http://www.devcurry.com" />');                   
  });
});
</script>
</head>

As you can see, we have used the jQuery wrap() function to wrap all italic elements with the anchor tag.

OUTPUT

jQuery Convert Link

On a side note, if you want to wrap the ‘contents’ of the text inside italics, search and also  put some filters before converting the text to links, use the following code:

<head>
<title>Convert Text to Link - DevCurry.com</title>
<script type="text/javascript" 
src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.1.min.js">
</script>     
<script type="text/javascript">
$(function () {
  $("#btn").click(function () {
     $('div.cls i').each(function () {
         $(this).contents().filter(function(){ /* code */  })
           .wrapAll('<a href="http://www.devcurry.com" />');
         });
     });
});
</script>
</head>

We are using the jQuery contents method to search through the elements, apply a filter and then use the wrapAll() function to wrap the anchor element around a set of matched elements.

Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

1 comment:

SUMIT SANCHETI said...

Is it possible to convert Link to Text. As I dont want to Hyperlink to function for SharePoint Page.