Ivan
Ivan

Reputation: 503

JavaScript: open links in new tabs

I would like to make a JavaScript that would put in each link the attribute target="_blank", so that the link would open in a new tab. This is how I did it:

function open_links_in_new_tabs() {
    var links = document.documentElement.getElementsByTagName( "a" );
    for(var link in links) {
        link.setAttribute("target", "_blank");
    }
}

window.onload = function() { open_links_in_new_tabs(); }

But, this doesn't work. Do you see where the mistake is?

Thanks,

Ivan

Upvotes: 1

Views: 357

Answers (4)

Prakash
Prakash

Reputation: 6602

Why don't you use jQuery, if you want to use jquery then here's the code:

$(document).ready(function(){
    $('a').attr("target","_blank");
})

Upvotes: 0

Sam Dufel
Sam Dufel

Reputation: 17598

I tested this on stackoverflow, and it seems to work on all the links :)

var links = document.getElementsByTagName("a");

for(var i = 0; i < links.length; ++i) {
  links[i].setAttribute('target', '_blank');
}

Upvotes: 0

Mark Bell
Mark Bell

Reputation: 29735

You are using the for... in loop slightly wrong here. Try this:

for(var link in links) {
    links[link].setAttribute("target", "_blank");
}

Edit: Though my example works in this situation, Boldewyn is right in that this will give unexpected results if your script is not operating on elements.

Upvotes: 0

Boldewyn
Boldewyn

Reputation: 82724

The foo in bar syntax doesn't work on NodeList objects (a.k.a. "the stuff returned by document.getElementsByTagName").

Use a plain old for (var i = 0; i < links.length; i++) (with links[i] instead of link, of course) loop and it should work.

Upvotes: 5

Related Questions