views:

35

answers:

3

I have links that are dynamically generated and I need to set the target for all of them. How could I do this with javaScript. I found something that looks like it should work using jQuery..

$("a").attr('target', '_top');

but I dont want to use a library for this and I imagine a couple of lines of javaScript would take care of it... I just dont know how to write it.

To further clarify what I am doing, the links are being generated with javaScript and a recommendation engine, ATG, and I am calling this in an iframe that I need to break out of to the top. I guess what I need is just a way to define all the links in the DOM, it does not have to be attached to a particular id. Is it possible to attach a dynamically generated attribute to a dynamically generated link? There is the possibility of building a custom render but I hope to avoid that route.

+2  A: 

I'm usually a jQuery man myself, but you are correct that such a small piece of code should not be library dependent. I may be a little rusty with my JavaScript without jQuery, but I think this should do it...

var anchors = document.getElementById('myDiv').getElementsByTagName('a');

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

This example assumes the jQuery selector you used is what you want to select. If you don't want to target a specific element with an id attribute, simply drop the getElementById() method.

alex
Thanks this looks like it should work however it does not in my situation ... I edited my post to describe better.
zac
+2  A: 

Something like this

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

for (var i = 0; i < anchorElements.length; i ++)
{
  anchorElements[i].setAttribute("target", "_top");
}
John Hartsock
thanks but same thing I said @alex
zac
A: 

Well I found the solution. Sorry I should have done more searching here before asking.

how-to-force-link-from-iframe-to-be-opened-in-the-parent-window

What worked for me was to use the object

<base target="_top" />
zac