Appending target="_blank" to links in an iframe without using <body onload>

Posted by CincauHangus on Stack Overflow See other posts from Stack Overflow or by CincauHangus
Published on 2010-12-23T08:48:22Z Indexed on 2010/12/23 8:54 UTC
Read the original article Hit count: 163

Filed under:
|
|
|

I'm trying to change the links in an iframe to load in a new window instead of the iframe itself. Currently I use this code in head:

$(document).ready(function() {
    var oIFrame = document.getElementById("iframeID");
    var oDoc = (oIFrame.contentWindow || oIFrame.contentDocument);
    if(oDoc.document) oDoc = oDoc.document;
    var links = oDoc.getElementsByTagName("a");
    for(var i=0; i<links.length; i++) { links[i].target="_blank"; }
});

However, the code above is triggered before the iframe is fully loaded with its contents. I know this code would work if it's triggered in the body onload attribute, but I'd like to avoid that method and implement it in a function or a file instead.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery