Bob John
Bob John

Reputation: 467

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.

Upvotes: 8

Views: 16713

Answers (3)

Michael Riccio
Michael Riccio

Reputation: 48

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.

Upvotes: 1

Meysam Izadmehr
Meysam Izadmehr

Reputation: 3262

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.

Upvotes: 3

Saravana Kumar
Saravana Kumar

Reputation: 3729

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>

Upvotes: 9

Related Questions