Retrieving links from webpage using javascript

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) {

But if I do this:


It returns the link for the first href

What am I doing wrong?

Here is the webpage I’m testing against:


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){

Example Here

For your example, you would have used:

for(link in document.links) {

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)) {