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:
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
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.
Tweet
1 comment:
Is it possible to convert Link to Text. As I dont want to Hyperlink to function for SharePoint Page.
Post a Comment