Use Javascript to open all links within a certain div in a new window

Here is the code that I use to set all the links within a certain div of a web page to open in a new window:

<script type="text/javascript">
var linktarget="_blank" //Specify link target added to links when set to open in new window
var formcache=document.targetmain
function applywindow(){
 if (typeof targetlinks=="undefined") return
 if (!formcache || (formcache && formcache.targetnew.checked)){
 for (i=0; i<=(targetlinks.length-1); i++)
 targetlinks&#91;i&#93;.target=linktarget
 }
 else
 for (i=0; i<=(targetlinks.length-1); i++)
 targetlinks&#91;i&#93;.target=""
 }
function collectElementbyClass(){
 if (!document.all && !document.getElementById) return
 var linksarray=new Array()
 var inc=0
 var alltags=document.all? document.all : document.getElementsByTagName("*")
 for (i=0; i<alltags.length; i++){
 if (alltags&#91;i&#93;.className=="<span style="color: #993300;">your-link-class</span>")
 linksarray[inc++]=alltags[i]
 if (alltags[i].className=="<span style="color: #993300;">your-div-class</span>"){
 var alldivlinks=document.all? alltags[i].all.tags("A") : alltags[i].getElementsByTagName("A")
 for (t=0; t<alldivlinks.length; t++)
 linksarray&#91;inc++&#93;=alldivlinks&#91;t&#93;
 }
 }
 return linksarray
 }
 if (formcache && formcache.targetnew.checked) //overcome IE bug, manually check checkbox that has "checked" attribute
 setTimeout("document.targetmain.targetnew.checked=true",100)
 var targetlinks=collectElementbyClass()
 applywindow()
</script>

 

Copy and paste that code into your web page just before the closing < body > tag.

Next, change your-link-class and your-div-class in the code to the class of the links or divs whose links you want to open in a new window.

Finally, simply add the class your-link-class (or whatever you changed it to) to any links that you want to open in a new window OR add the classĀ your-div-class (or whatever you changed it to) to the div whose links you want to open in a new window.

For example: if you change your-link-class to blank, you would add this class to each link you want to open in a blank window:

<a href="http://yourwebsite.com" class="blank">Your Link</a>

And if you change your-div-class to blank-div, you would add the class to the entire div whose links you want to open in new windows:

<div id="mydiv" class="blank-div">
<a href="http://firstwebsite.com">Link #1</a>
<a href="http://secondwebsite.com">Link #2</a>
<a href="http://thirdwebsite.com">Link #3</a>
</div>

Each link in this div will automatically open in a new window.

Credit for this script goes to Dynamic Drives, the article where I found this code is at http://www.dynamicdrive.com/dynamicindex8/newwindow3.htm.