关于getelementsbytagname的Javascript问题

时间:2013-11-20 14:12:41

标签: javascript

我在使用此代码时遇到了一些问题:

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

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

第一个日志正确地告诉我:

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

但是第二个日志告诉我:

undefined

我不明白原因,它可以向我展示dom中的第一个元素输入!

1 个答案:

答案 0 :(得分:1)

问题出现在document.getElementsByTagName的返回值是实时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

将它与您在文档准备好之前调用代码(因此在列表中有项目之前)以及控制台代码中的已知错误相结合,可以在调用{{1之后“显示状态中的对象已经完成,你有你正在经历的确切行为。

重申:

console.log

编辑:要获得一个好的日志,您可以在记录对象时对其进行字符串化,将其转换为正确记录的原始值:

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

PS: 链接到解释控制台错误的博客文章: http://techblog.appnexus.com/2011/webkit-chrome-safari-console-log-bug/

链接到请求修复控制台错误的问题: How can I change the default behavior of console.log? (*Error console in safari, no add-on*)