1

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!

Stefano Maglione
  • 3,946
  • 11
  • 49
  • 96
  • 2
    that should perfectly work as you expect- are you sure nothing happens to `lista_inputs` between the two log calls ? – geevee Nov 20 '13 at 14:15
  • That should work... try on this site: `document.getElementsByTagName("input")[0]` – megawac Nov 20 '13 at 14:15
  • 1
    Your code is fine. check this http://jsfiddle.net/kbJpj/19/ – Murali Murugesan Nov 20 '13 at 14:15
  • 1
    @Murali that's assuming we've seen _all_ of his code. In practise the nodelist will be a _live_ nodelist, so any changes that are made to the DOM between the two accesses might change its contents. – Alnitak Nov 20 '13 at 14:20

1 Answers1

1

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

Community
  • 1
  • 1
Tibos
  • 27,507
  • 4
  • 50
  • 64