最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - object HTMLcollection[0] keeps returning undefined - Stack Overflow

programmeradmin1浏览0评论

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. And if I try something like alert(document.getElementsByClassName("my-list")[0]) I get undefined. How can I get the first href in the list? So it would be "1" in this case.

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. And if I try something like alert(document.getElementsByClassName("my-list")[0]) I get undefined. How can I get the first href in the list? So it would be "1" in this case.

Share Improve this question asked Feb 12, 2015 at 9:18 Bob JohnBob John 4672 gold badges5 silver badges14 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 9

Check this in Fiddler. Place the document.getElementsByClassName("my-list") in a round bracket and the add the index [0] to it.

**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. In this case, you saw HTMLCollection; however, the items would be empty.

move the script to the bottom of the HTML body.

Also, just be sure to check your code, I had this problem from using 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.

发布评论

评论列表(0)

  1. 暂无评论