开发者

Set all link targets for a page

开发者 https://www.devze.com 2022-12-30 11:17 出处:网络
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..

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.


Something like this

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

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


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.


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" />
0

精彩评论

暂无评论...
验证码 换一张
取 消