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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With