change <a> target to "_blank" depending on href

Christian picture Christian · Sep 1, 2010 · Viewed 21.1k times · Source

I'm trying to sort through the links on my page and make some of them open into a new window, depending on their URL. This is the code I have. It doesn't seem to be working. Can you see why?

function MakeMenuLinksOpenInNewWindow() {
    var links = document.getElementsByTagName("a");
    for (var i = 0; i < links.length; i++) {
        if (links[i].href == "http://testtesttest.org/")
            links[i].target = "_blank";
    }
}
MakeMenuLinksOpenInNewWindow();

Answer

Darin Dimitrov picture Darin Dimitrov · Sep 1, 2010

Make sure that when you call this function the DOM has been loaded:

window.onload = MakeMenuLinksOpenInNewWindow;

or:

<body onload="MakeMenuLinksOpenInNewWindow();">