How to Use jQuery to Add rel="nofollow" and Open Links in a New Tab
If you're working with websites, you may have come across the need to open external links in a new tab using jQuery. Additionally, you might want to add rel="nofollow"
to these links to help improve your website's SEO (Search Engine Optimization). In this blog post, we will discuss how to implement both functionalities using jQuery.
Prerequisites
- A basic understanding of HTML and CSS.
- Familiarity with JavaScript and jQuery.
Setting Up
First, let's ensure that you have included the jQuery library in your project. Add the following line within the <head>
tag of your HTML file:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
Creating the JavaScript File
Create a new JavaScript file, let's call it external_links.js
, and link it in your HTML file:
<script src="external_links.js"></script>
Now, add the following code to your external_links.js
file:
$(document).ready(function() {
$('a[href^="http"]').each(function() {
$(this).attr('target', '_blank'); // Open in a new tab
if ($(this).is('[rel!="nofollow"]')) { // If not already rel="nofollow"
$(this).attr('rel', 'nofollow'); // Add rel="nofollow"
}
});
});
This code does the following:
- Waits for the document to be ready before executing any code.
- Selects all anchor tags whose href attribute starts with "http" (assuming you want to apply this only to external links).
- Adds the
target="_blank"
attribute to each selected link, which opens it in a new tab. - Checks if the current link already has the
rel="nofollow"
attribute. If not, it adds that attribute as well.
Conclusion
With this simple setup, you can easily use jQuery to open external links in a new tab and add rel="nofollow"
to improve your website's SEO. Don't forget to test your code thoroughly and ensure compatibility with various browsers and devices. Happy coding!