tekknolagi
tekknolagi

Reputation: 11022

set attribute of every anchor in document

I'm trying to set the target of every link in a page. I'm currently trying:

var x = document.getElementsByTagName('a')
for (i in x)
    i.setAttribute('target', '_blank');

But I get a TypeError. It works when I setAttribute on the x[0], but not how I did it above. Suggestions?

Upvotes: 1

Views: 855

Answers (1)

Rob W
Rob W

Reputation: 349132

Refer to x[i] instead of i. i returns the index of the link.

For array-like objects, it's recommended to use for(var i=0; i<x.length; i++) instead of for(i in x).

Your code can be written more efficiently using the code below, because not every a element is a link:

var x = document.links;
for(var i=0, l=x.length; i<l; i++){
    x[i].setAttribute("target", "_blank");
}

Upvotes: 4

Related Questions