2

I'm new to javascript and simply trying to pull links from a webpage so I'm doing the following:

for(link in document.links) { 
   console.log(link.getAttribute("href");
}

But if I do this:

document.links.item(0).getAttribute("href")

It returns the link for the first href

What am I doing wrong?

Here is the webpage I'm testing against: http://en.wikipedia.org/wiki/JavaScript_syntax

nullByteMe
  • 6,141
  • 13
  • 62
  • 99

3 Answers3

4

Just get the elements by tag name and avoid the for in loop.

var links = document.getElementsByTagName('a'),
    i;

for(i = 0; i < links.length; i += 1){
    console.log(links[i].getAttribute("href"));
}

Example Here


For your example, you would have used:

for(link in document.links) { 
   console.log(document.links[link].getAttribute("href"));
}

While that technically works, it returns prototype properties in addition to the link elements. This will throw errors since .getAttribute("href") won't work for all the return elements.

You could use the hasOwnProperty() method and check.. but still, i'd avoid the for in loop.

for (link in document.links) {
    if (document.links.hasOwnProperty(link)) {
        console.log(document.links[link]);
    }
}
Community
  • 1
  • 1
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
2
document.links.item

is an array of items.

document.links.item(0) gets the first item in that array.

document.links.item(1) gets the second item in that array.

To answer your question, what you are doing wrong is that you are not looping the links.item array as you did in your first example.

Design by Adrian
  • 2,185
  • 1
  • 20
  • 22
  • So document.links is not iteratively returning each link in document.links? – nullByteMe Sep 06 '14 at 17:18
  • No. Only for loops do iterate. document.links.item does, however, give you the whole collection of items at once. But document.links.item.getAttribute("href") will be undefined, because getAttribute() is not a function of the array. – Design by Adrian Sep 06 '14 at 17:22
  • I see and that makes sense now. document.links was not returning a link object, so there is no getAttribute() function available. So I need to return the document.links.items to get each link object. – nullByteMe Sep 06 '14 at 17:27
  • @inquisitor Correct. Just as you did at first. I'd like to suggest Josh's answer, though :) – Design by Adrian Sep 06 '14 at 17:28
1

In your code, you are accessing item 0 and only getting the href from that. For that reason, you will only get one link.

What you probably want to do is get the href for all of the of the links at once

var hrefs = [], i
for (i=0;i<document.links.length;++i) {
    hrefs.push(document.links.item(i).getAttribute('href'))
}

Then your hrefs array will contains all the urls

Strikeskids
  • 3,932
  • 13
  • 27