0

Is this code the best solution to get all links in a page in an array:

 var allLinks = document.getElementsByTagName('a');

Or is there a better solution than this?

After this, how can I open all links in the array "allLinks[i]" in new tabs?

Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
Saad
  • 103
  • 1
  • 4

1 Answers1

2

Just attach a new 'target' attribute to all the 'a' html tags and Chrome will open all the links in a new tab by default.

With jQuery the answer is easy.

$('a').each(function(){ $(this).attr('target', '_blank'); });

Or in pure javascript

var allLinks, link, _i, _len;

allLinks = document.getElementsByTagName('a');

for (_i = 0, _len = allLinks.length; _i < _len; _i++) {
  link = allLinks[_i];
  link.setAttribute('target', '_blank');
}

Or in coffee script

allLinks = document.getElementsByTagName('a')

for link in allLinks
 link.setAttribute 'target', '_blank'