简体   繁体   English

对象 HTMLcollection[0] 不断返回 undefined

[英]object HTMLcollection[0] keeps returning undefined

Suppose we have something like:假设我们有类似的东西:

<a href="1" class="my-list">1</a>
<a href="2" class="my-list">2</a>
<a href="3" class="my-list">3</a>

When I try something like当我尝试类似的东西时

alert(document.getElementsByClassName("my-list"))

I get object HTMLCollection .我得到object HTMLCollection And if I try something like alert(document.getElementsByClassName("my-list")[0]) I get undefined .如果我尝试类似alert(document.getElementsByClassName("my-list")[0])我会得到undefined How can I get the first href in the list?如何获得列表中的第一个href So it would be "1" in this case.所以在这种情况下它将是"1"

Check this in Fiddler .Fiddler 中检查这个。 Place the document.getElementsByClassName("my-list") in a round bracket and the add the index [0] to it.document.getElementsByClassName("my-list")放在圆括号中,并将索引 [0] 添加到它。

 **UPDATE**: Use `window.onload` to perform operations after all DOM elements are loaded. window.onload = function() { alert((document.getElementsByClassName("my-list"))[0]) }
 <a href="http//:www.google.com/" class="my-list">1</a> <a href="http//:www.facebook.com/" class="my-list">2</a> <a href="http//:www.sample.com/" class="my-list">3</a>

It could happen if you add the script in the HTML header.如果您在 HTML 标头中添加脚本,则可能会发生这种情况。 In this case, you saw HTMLCollection ;在本例中,您看到了HTMLCollection however, the items would be empty.但是,这些项目将为空。

move the script to the bottom of the HTML body.将脚本移动到 HTML 正文的底部。

Also, just be sure to check your code, I had this problem from using querySelector.另外,请务必检查您的代码,我在使用 querySelector 时遇到了这个问题。 If you use querySelector it only returns one element (which will return undefined when iterating), while querySelectorAll creates a html collection which you can iterate through.如果您使用 querySelector 它只返回一个元素(迭代时将返回 undefined ),而 querySelectorAll 创建一个可以迭代的 html 集合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM