Force all hyperlinks tags to target a new window

In this javascript tutorial we will learn how to force all hyperlink tags to target a new window. Sometimes we want to target all hyperlink tags to target a new window, normally in case of RSS Feeds.

Let’s consider we have a webpage where we have 100 hyperlinks of RSS feeds and these 100 hyperlinks are opening in a parent window, now we want to target these hyperlinks in a new window so without going in each and every hyperlink and write this code target="_blank" just use this below mention javascript function and call this javascript function in body onload event then all the hyperlinks will target a new window.


function ForceLinks()

{
// It will tell u how many no of tags your code have
var linkslength= document.getElementsByTagName('a').length;

// Putting tag in links variable to use it for array purpose
var links=document.getElementsByTagName('a');

for(var i = 0; i < linkslength; ++i)

{

links[i].setAttribute('target','_blank');

}

}

Now just call this function in your body onload event<body önload="ForceLinks();"> </body>

So this is the way we can force all hyperlink tags to target a new window in javascript.

0 comments: