Tom Burris Tom Burris - 2 years ago 90
Javascript Question

Array Index Value Undefined, Array Isn't

If you need more background information just ask.


<script type="text/javascript>
var buttons = document.getElementsByClassName("_jvpff");
console.log(buttons[0]); //added after error from command below


enter image description here


enter image description here

The array contains valid elements, but when trying to access an element with an index, it returns undefined.


Answer Source

document.getElementsByClassName returns a live HTMLNodeList which updates as elements become available, and the console has its own quirks for when the contents of an object are evaluated and updated. If button[0] is undefined at the time of trying to access it, then it's undefined at that time. Which means you need to wait with your script execution until the DOM is ready and the element actually exists. Either put your scripts at the bottom of the page, or wait for the DOM to be ready by listening for the DOMContentLoaded event.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download