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.




About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

1 comment:

Unknown said...

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