为什么getElementsByTagName()返回html集合,而getElementsByTagName()[0]返回未定义? [英] Why is getElementsByTagName() returning an html collection, but getElementsByTagName()[0] returning undefined?

查看:74
本文介绍了为什么getElementsByTagName()返回html集合,而getElementsByTagName()[0]返回未定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发使用内容脚本的chrome扩展程序.我正在尝试获取页面的元素,但正在获取从未遇到过的结果.页面加载后,这就是我正在运行的代码.

I am working on a chrome extension that uses content scripts. I am attempting to get an element of a page, but I am getting results I have never encountered. Here is the code I am running, once the page loads.

var iframe = document.getElementsByTagName("iframe");
console.log(iframe);
console.log(iframe[0]);

第一个日志返回一个长度为1的HTML集合,第一个元素完全定义为iframe元素.

The first log returns an HTML Collection with a length of 1, and the first element is defined fully as an iframe element.

第二条日志返回未定义.

The second log returns undefined.

我肯定想念一些明显的东西,有人知道发生了什么事吗?

I must be missing something obvious, anyone know what is going on?

我也尝试了项目(0),但结果否定.

I have also attempted item(0), with negative results.

我尝试获取ID,类和其他引用DOM元素的方法,它们都可以工作.但是类在这里有相同的问题,它将返回一个元素数组,但是如果我尝试引用第一个元素,则始终是未定义的.

I have attempted getting IDs, classes, and other methods of reference DOM elements, they all work. But classes has the same issue here, it will return an array of elements, but if I attempt to reference the first element, it is always undefined.

推荐答案

问题是它是Live HTMLCollection.如此更新!您是在元素存在之前对其进行引用.

Problem is it is a Live HTMLCollection. So it updates! You are referencing it before the element exists.

<script>
  var iframe = document.getElementsByTagName("iframe");
  console.log("1", iframe);
  console.log("2", iframe[0]);
</script>
<iframe></iframe>
<script>
  console.log("3", iframe);
  console.log("4", iframe[0]);
  iframe[0].remove();
  console.log("5", iframe);
  console.log("6", iframe[0]);
</script>

这篇关于为什么getElementsByTagName()返回html集合,而getElementsByTagName()[0]返回未定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆