Tips & Tricks

Find External Links Using jQuery

What if you want to stylize all your external link with some different style. There are two options.

  1. Seach for each link and give different class to it
  2. Follow this article

Yes, This article is about to explain about searching for all external links and add one more class to it.

Here we will use jQuery to search all the external links. Here I will show different technique to search for all external links. We will search for all external links and add one more class “external_link” to those links.

Technique 1

[cc lang=”javascript”]
$(‘a’).filter(function()
{
return this.hostname && this.hostname !== location.hostname;
}).addClass(“external_link”);
[/cc]

Technique 2

[cc lang=”javascript”]
$(‘a’).each(function()
{
var reg_exp = new RegExp(‘/’ + window.location.host + ‘/’);
if (!reg_exp.test(this.href))
{
// External Link Found
this.addClass(“external_link”)
}
});
[/cc]

So this is what we can do to find all external links and stylize them bit differently. Hope this will be useful for you when you really this. If you have more techniques to achieve this then its great to share over here.

Shares:
  • […] This article is about to explain about searching for all external links and add one more class to it.    Javascript Read the original post on DZone… […]

    Reply
  • […] link esterni con jQuery In questo post vi proporrò qualche snippet (tratto da questo interessante articolo) basato sul framework Javascript jQuery per svolgere un’operazione che potrebbe ritornarvi […]

    Reply
  • Michael Dorf
    April 7, 2012 at 4:48 am

    A very elegant solution. Quite handy in posts when you need to differentiate your own internal links from references to other sites. Thanks!

    Reply
  • melek rebai
    melek rebai
    April 25, 2012 at 4:54 am

    i love jquery.
    i can’t imagine my life without it, i use the first one.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *