Opening links in a new tab or window I've got a lot of links (150+) in an href (here I can only post 2) and I want them to be opened in a new tab or window. I've got this piece of code that works, but before I add it to my website and before I add it to a lot of articles of mine (250+), I want to make sure the syntax of the code is 100% correct. Also, do I need the &lt;p&gt;?

&lt;script&gt; 
window.onload = function(){
    var a = document.getElementById('links').getElementsByTagName('a');
    for (var i=0; i&lt;a.length; i++){
         a[i].setAttribute('target', '_blank');
    }
} 
&lt;/script&gt;

&lt;div id="links"&gt;
    &lt;p&gt;&lt;a href="http://www.google.com/" &gt;test&lt;/a&gt;&lt;/p&gt;
    &lt;p&gt;&lt;a href="http://www.google.com/" &gt;test&lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;
The code itself is fine, though I would flip it, first html, then the javascript (without the window.onload).

AN example to explain why: If you have a huge image and a slow connection the loading takes say 5 seconds. These 5 seconds all your anchors don't have the target="_blank" and if a user clicks they still leave your website.

I would not use this method meself (unless I have to) . 
If you use AJAX to load content with anchors, those anchors will not have the target="_blank" either. This will require a bit more advances problem solving. If you want some links to be ignored, you can't with the current code. There are more small problems that will pop up which are all to minor to sum up here, but in the end are all just very ennoying.

I recommend that you do not rely on this method. Just take some time and update the content. I assume you have that in a datase, just FIND() and REPLACE(). Make it permanent.