find a location for property in a new city

Friday, 11 January 2013

Add rel="nofollow" to all external links with one line of jQuery

You may want to change all external links on a page to do something different such as add a target="_blank" to each one or add rel="nofollow" to every external link. This post will show you how this can be done in one line of jQuery!

SEO SEO SEO... How tiresome a concept... Anyway, people make their living with it apparently and while that is the case I get all kinds of weird requirements like this. This time I had to add rel="nofollow" to all external links for latest whim of an SEO consultant.

Since SEO requirements seem to chop and change fairly unpredictably I wanted to add rel="nofollow" to all external links in the quickest and least interfering way possible. I managed it with one line of jQuery so that is fairly innocuous and I can just remove it if it needs to be undone at some point. This can be used to add target="blank" to also.

Add rel="nofollow" to all external links

$("div.content a[href^='http']:not([href*='mysite.co.uk'])").attr("rel", "follow");

Add target="_blank" to all external links

$("div.content a[href^='http']:not([href*='mysite.co.uk'])").attr("target", "_blank");

Hope this helps you spend as little time on this as possible :)

Update:

I did some reasearch into whether adding a nofollow in this way will work on Google and came to the conclusion that it probably wont. Colin Asquith commented similar thoughts. So this should probably be considered if using this for adding rel="nofollow" to links but technically this is a good way of going about it or anything similar like adding target="_blank" for example.

Follow britishdev on Twitter

6 comments:

  1. But doesn't this just add "nofollow" to links using JavaScript after the page has loaded? When a bot spiders your page it will actually get the links before they have had this attribute added, so will be treated as normal links.

    Basically if you have a website, and it's built up some credibility, sites you link out to get some of that - so often you want to use "nofollow" for something like a comments page so when people add links in comments they aren't doing it for their own SEO benefit.

    ReplyDelete
    Replies
    1. You know what? I think you're on to something. I actually looked into this myself as you can never be sure how Google works since it apparently does execute JavaScript. I came to the definitive solution that it *probably* wont work in the way I intended. As in it will affect the DOM but it will *probably* be too late for Google to care.

      However, I forgot I wrote a blog post about it so I should probably correct that.

      Delete
  2. Also- a pleasure to see a .NET/SQL blog by a fellow developer and a fellow Colin :) we're taking over.

    ReplyDelete