简体   繁体   中英

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

The foo in bar syntax doesn't work on NodeList objects (aka "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.

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.

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');
}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM