Stefano Maglione
Stefano Maglione

Reputation: 4150

Javascript issue on getelementbytagname

I'm having some trouble with this code:

var lista_input = document.getElementsByTagName("input");

console.log(lista_input);
console.log(lista_input[0]);

The first log correctly show me:

[item: function]
0: input
1: input
length: 2
__proto__: NodeList

but the second log show me:

undefined

I don't understand the reason,it could show me the first element input in dom!

Upvotes: 1

Views: 62

Answers (1)

Tibos
Tibos

Reputation: 27823

The problem occurs from the fact that the return value of document.getElementsByTagName is a live NodeList:

var l = document.getElementsByTagName('div');

console.log(l[0]); // undefined

var d = document.createElement('div');
document.body.appendChild(d);

console.log(l[0]); // div

Combine that with the fact that you call the code before the document is ready (so before there are items in the list) and the known bug in the Console code that can show objects in a state after the call to console.log is made and you have the exact behavior you are experiencing.

To reiterate:

var lista_input = document.getElementsByTagName("input");
// lista_input is a live NodeList with 0 elements

console.log(lista_input); // will print the lista_input object at a later point
console.log(lista_input[0]); // will print undefined at a later point

/* time passes, dom is loaded */
// lista_input now has the inputs you expect it to have

/* time passes */
// logs are now shown in Console

EDIT: To get a good log, you can stringify the object when logging it, turning it into a primitive value that gets logged correctly:

var lista_input = document.getElementsByTagName("input");

console.log(JSON.stringify(lista_input)); // {"length":0} - empty list
console.log(JSON.stringify(lista_input[0])); // undefined

PS: Link to a blog post explaining the Console bug: http://techblog.appnexus.com/2011/webkit-chrome-safari-console-log-bug/

Link to a question requesting a fix to the Console bug: How can I change the default behavior of console.log? (*Error console in safari, no add-on*)

Upvotes: 1

Related Questions