Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all href links in DOM

I need to write code that puts all of the href links from a webpage into an array. Here's what I have so far:

var array = [];
var links = document.links;
for(var i=0; i<links.length; i++) {
  array.push(links[i].href);
}

However, this does not work on a page like Gmail's inbox, because the some of the links are within an iframe. How can I get ALL of the links, including the ones inside the iframe?

Also, this is for a google chrome extension. In the manifest, I have all_frames set to true - does this make a difference?

Thanks

like image 505
user1137778 Avatar asked Jan 19 '12 08:01

user1137778


Video Answer


2 Answers

One thing to remember that

  1. document.links
  2. document.images
  3. document.forms
  4. document.forms[0].elements
  5. document.getElementsByName()
  6. document.getElementsByClassName()
  7. document.getElementsByTagName()

are live queries to DOM objects, therefore in forLoops it may significantly slow down your execution (as i < links.length is queries on each for cycle), if you check the array length like this:

var array = [];
var links = document.getElementsByTagName("a");
for(var i=0; i<links.length; i++) {
    array.push(links[i].href);
}

instead you better do this:

var array = [];
var links = document.getElementsByTagName("a");
for(var i=0, max=links.length; i<max; i++) {
    array.push(links[i].href);
}
like image 57
DmitrySemenov Avatar answered Sep 20 '22 21:09

DmitrySemenov


Surely you're going to get 'arr is not defined' with your code to begin with?

var array = [];
var links = document.links;
for(var i=0; i<links.length; i++) {
    arr.push(links[i].href);
}

Try:

var array = [];
var links = document.getElementsByTagName("a");
for(var i=0; i<links.length; i++) {
    array.push(links[i].href);
}
like image 21
Hogsden Avatar answered Sep 20 '22 21:09

Hogsden