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

3 Answers 3

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]);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Your answer was also very helpful to me. Thanks!
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.

4 Comments

So document.links is not iteratively returning each link in document.links?
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.
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.
@inquisitor Correct. Just as you did at first. I'd like to suggest Josh's answer, though :)
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.