Tom Burris
Tom Burris

Reputation: 390

Array Index Value Undefined, Array Isn't

If you need more background information just ask.

Javascript:

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

Console:

enter image description here

HTML:

enter image description here

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

Thanks.

Upvotes: 2

Views: 468

Answers (1)

deceze
deceze

Reputation: 522015

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.

Upvotes: 6

Related Questions