Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 604
Bob John Avatar asked Feb 12 '15 09:02

Bob John


People also ask

Why is HTMLCollection empty?

This is because your JS is running before the elements are rendered to the DOM. I bet the script you have running is loaded before the <body> of your html.

What is object HTMLCollection in JavaScript?

An HTMLCollection is a collection of document elements. A NodeList is a collection of document nodes (element nodes, attribute nodes, and text nodes). HTMLCollection items can be accessed by their name, id, or index number. NodeList items can only be accessed by their index number.

What is HTMLCollection?

The HTMLCollection interface represents a generic collection (array-like object similar to arguments ) of elements (in document order) and offers methods and properties for selecting from the list.

How do I find the length of a HTMLCollection?

The length() Property is used to return the collection of all HTML elements in a document. It is read-only property and is quite useful when a user wants to loop through an HTML Collection. Return Value: It returns a number which represent the number of all elements in a HTML Collection.


2 Answers

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>
like image 91
Saravana Kumar Avatar answered Sep 28 '22 03:09

Saravana Kumar


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.

like image 40
Meysam Izadmehr Avatar answered Sep 28 '22 01:09

Meysam Izadmehr