views:

29

answers:

2

I want open certain links in a new tab. Since I can't set it directly into the a tag, I want to pot the link into span tags with a ceratin class name and set the target attribute via javascript.

I thought this would be easy, but I can't get it working:

addOnloadHook(function () {
  document.getElementByClassName('newTab').getElementsByTagName('a').setAttribute('target', '_blank');
});

<span class="newTab"><a href="http://www.com"&gt;Link&lt;/a&gt;&lt;/span&gt;

What am I doing wrong?

+2  A: 

document.getElementByClassName does not exist, the correct function is document.getElementsByClassName (note the extra s). It returns an array of matching nodes, so you've to give an index:

addOnloadHook(function () {
  document.getElementsByClassName('newTab')[0].getElementsByTagName('a')[0].setAttribute('target', '_blank');
});
Lekensteyn
Eek. I feel dumb. Thanks!
Martin
A: 

but you might need to iterate through every span with the specified class ('newTab') on the page for it to work:

addOnLoadHook(function(){

  var span = document.getElementsByClassName('newTab');

  for(var i in span) {
    span[i].getElementsByTagName('a')[0].setAttribute('target','_blank');
  }

});

in case you'll have more than 1 anchor tag in a span you'd also have to iterate through the anchor tags like this:

addOnLoadHook(function(){

  var span = document.getElementsByClassName('newTab');

  for(var i in span){
    var a = span[i].getElementsByTagName('a');
    for(var ii in a){
      a[ii].setAttribute('target','_blank');
    }
  }

});
Jonas