简体   繁体   中英

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 . 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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