Auto open active links in div on new tab

时间:2016-10-19 13:35:36

标签: javascript html css

Been trying to automatically open active links in a div on a new tab when page is loaded

I can't edit the links to add ids or classes, it would have been much easier this way:

  document.getElementById('yourLinkID').click();

if I could add ids to the links but am not allowed to.

On the page I have

 <div id="boss" class="boss">
 <a href="http://example.com" title="Example.com">Example.com</a>
 <a href="http://example.com" title="Example.com">Example.com</a>
 <a href="http://example.com" title="Example.com">Example.com</a>
 <a href="http://example.com" title="Example.com">Example.com</a>
 </div>

This would do it in JQuery,

$(function(){
  $("#myDiv a").attr("target","_blank");
});

Any help with this in JavaScript? A working JS fiddle would be appreciated.

2 个答案:

答案 0 :(得分:1)

Get the child-nodes of you #boss-element. Than open each of them in a new window/tab (without using jQuery):

var links = document.getElementById("boss").getElementsByTagName("a");

for(var i = 0; i < links.length; i++) {
  window.open(links[i].getAttribute("href"), "_blank");
}
<div id="boss" class="boss">
 <a href="http://example.com" title="Example.com">Example.com</a>
 <a href="http://example.com" title="Example.com">Example.com</a>
 <a href="http://example.com" title="Example.com">Example.com</a>
 <a href="http://example.com" title="Example.com">Example.com</a>
 </div>

Note: The code doesn't run, because SO prevents popups from being opened.

There might be a problem on running this code, if the JS is executed, before them DOM is fully loaded. You can prevent this from happending, by either wrapping the JS in a function, that you call on <body onLoad="yourFunctionName()" or by including the script at the very bottom of your site, right before the closing </body>-Tag.

EDIT:

Its not that easy to only open unvisited links. JavaScript does not allow to select links by ":list"-selector (what would return only unvisited ones). You would need to store, what links you already opened (in a persistent file or something) and compare every list in your element with that stored list, to get unvisited links. At least, that would be my approach to accomplish this.

答案 1 :(得分:0)

JS Fiddle here

function setAttr(){
  var theLinks = document.getElementById("mydiv").getElementsByTagName("a");

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

setAttr();