Adding the nofollow attribute to external links with jQuery

Filed under: jQuery

comments (13) Views: 9,870

Today over at House of Fusion Jeff Becker asked:

I'm looking for a working rel="nofollow" regex to modify links. For example:
Goto <a href="http://google.com">Google</a> now!
turning it into:
Goto <a href="http://google.com" rel="nofollow">Google</a> now!

While Jeff was looking specifically for a ColdFusion option, I wanted to let him know how simple this would be to add using jQuery. First, the links:


<a href="/somepage.html">This is an internal link</a>
<br /><br />
<a href="http://google.com">And this is an external link, with no follow</a>

Secondly the 45 characters of jQuery needed to convert all external facing URLs and add the nofollow parameter


$('a[href^="http"]').attr('rel','nofollow');

All hail jQuery.

See the results in action.

It was pointed out to me on Twitter, and via the comments in this post, that this particular example might not be the best use of jQuery's magic. Why? Because search engines / spiders don't execute JavaScript. This, however, is incorrect...or at least not one hundred percent accurate. I did a quick search and found several search engines that reportedly execute JavaScript code. So, while there are FAR better uses for jQuery's magic, this post stands as a good example of how to add attributes to elements using jQuery.

Amazon logo

If this article was interesting, or helpful, or even wrong, please consider leaving a comment, or buying something from my wishlist. It's appreciated!

comments powered by Disqus
coach outlet online jordan 13 grey toe beats by dre cyber monday michael kors black friday beats by dre cyber monday jordan 6 black infrared north face cyber monday michael kors cyber monday north face black friday coach outlet black infrared 23 13s north face cyber monday jordan 6 black infrared north face black friday coach cyber monday jordan 11 legend blue north face cyber monday black infrared 6s lebron 12 north face black friday jordan 11 legend blue louis vuitton outlet jordan 13 grey toe grey toe 13s beats by dre black friday coach black friday jordan 13 grey toe coach cyber monday uggs black friday jordan 13 black infrared 23 uggs cyber monday barons 13s uggs black friday beats by dre cyber monday black infrared 6s jordan 13 bred jordan 13 black infrared 23 north face black friday black infrared 6s jordan 11 legend blue michael kors black friday jordan 13 grey toe coach black friday michael kors black friday michael kors cyber monday beats by dre cyber Monday north face cyber monday coach black friday michael kors cyber monday beats by dre cyber Monday north face black friday beats by dre black friday lululemon black friday uggs black friday jordan 13 bred coach cyber monday beats by dre black friday uggs black friday coach black friday black infrared 6s