1

I created an array using:

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

If I do:

console.log(links.length);  

I get: 2.

However, if I do:

console.log(links);

I get an object that looks like this:

[a.elm-skip-link, a]

and when I expand this object, there are 33 link objects in it.

Why does the length of the links object change? If it is an array, doesn't it retain the size it is when created?

Here is all the code I'm using:

var links = document.getElementsByTagName('a');
console.log('links:');
console.log(links);
console.log('length:');
console.log(links.length);  

BTW: I'm trying to select a specific link on the page that does not have an "id" or "class" attribute, so I'm needing to get all the links, then loop through them to find the one that has the "title" attribute I'm looking for. However, when I try to loop through this "links" object, the loop only runs twice, despite there being 33 links on the page.

Tyler Jones
  • 1,283
  • 4
  • 18
  • 38
  • first, that's not an array, it's a [node list](https://developer.mozilla.org/en-US/docs/Web/API/NodeList) – WhiteHat Aug 20 '15 at 22:46
  • 1
    Just a note: there is a *document.links* collection that is all the links in a page. A elements aren't necessarily links. Also, [*getElementsByTagName*](http://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-A6C9094) returns a [*NodeList*](http://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-536297177), not an Array. – RobG Aug 20 '15 at 22:47
  • Because of the behavior of the HTMLCollection (which I did not know about), this question is not a duplicate of the console.log sync or async question. I know that console.log is not async, but I didn't know about the HTMLCollection object's special behavior. – Tyler Jones Aug 20 '15 at 22:59

1 Answers1

3

getElementsByTagName does not actually return an array, it returns an array like object which is live HTMLCollection.

Live meaning that any time the DOM is modified, the collection (or returned array like object) is modified.

So, if I had to venture a guess, I would assume that your DOM was not fully loaded when you run the first call to this function. The set it returns only contains two of the elements, and they are sent to the console.

Later, when you expand on the set, the DOM has been modified, and you see the resulting 33 elements.

Travis J
  • 81,153
  • 41
  • 202
  • 273
  • I did not know about the live HTMLCollection object. This was the problem. I wrapped my call in a document.ready interval, and it worked correctly. Thanks! – Tyler Jones Aug 20 '15 at 22:54