JavaScript

How to Set the Target Attribute of an Anchor Tag to “_blank” with jQuery: Targeting Specific Link Strings

In the realm of modern web design and development, various technologies and tools are utilized to provide a consistent user experience. Particularly, on large websites or sites with multiple pages, there may be a need to change link attributes in bulk. This article details how to use jQuery’s .attr method to change the target attribute of anchor tags on a page to “_blank” all at once.

JavaScript Code Using the .attr Method

First, include the necessary jQuery library on your page. The following code is an example of loading jQuery from Google’s CDN.

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

 
Next, add a script that uses jQuery to manipulate the links on the page. In this example, the target attribute of anchor tags containing the string “/category/” in their URL is set to “_blank”.

<script type="text/javascript">
$(function(){
     $("a[href^='/category/']").attr("target","_blank");
});
</script>

 
The key part of this script is the selector $(“a[href^=’/category/’]”). This selects all anchor tags whose href attribute starts with “/category/”. The .attr(“target”,”_blank”) then changes their target attribute to “_blank”.

Example HTML

Below is a sample HTML that includes anchor tags targeted for change.

<div class="clWrap">
    <h1>Change the target attribute of anchor tags containing specific strings in their URL to "_blank"</h1>
    <ul>
        <li class="cat-item cat-item-36"><a href="/category/css">CSS</a></li>
        <li class="cat-item cat-item-2"><a href="/category/javascript">JavaScript</a></li>
        <li class="cat-item cat-item-3"><a href="/category/jquery">jQuery</a></li>
        <li class="cat-item cat-item-53"><a href="/category/php">PHP</a></li>
    </ul>
</div><!--/clWrap-->

Demo Page for Changing the Target Attribute of Anchor Tags Using jQuery’s .attr

To experience this technique in action, refer to the demo page below.

Demo Page for Changing the Target Attribute of Anchor Tags Using jQuery’s .attr

Summary

Using this method makes it very easy to change link attributes in bulk on sites with many pages or sites with links that meet specific criteria. Furthermore, this method can be applied to change attributes of tags other than anchor tags in a similar manner. As such, jQuery provides a powerful tool for efficiently manipulating elements on a web page. Be sure to incorporate it into your daily development work.

*Please use this information at your own risk. Do not use the Google Analytics tag from the demo page.*