0

I am running the following script:

const myVar = document.getElementsByClassName('pricing-custom-header-links');
console.log(myVar);
console.log(myVar[0]);

and I get the output:

----------------------------------------
HTMLCollection []
    0: li.headerLink.vdm.keep.pricing-custom-header-links 
    1__proto__: HTMLCollection
-----------------------------------------
undefined
-----------------------------------------

This seems to make no sense. The first log tells me that we have an array-like object, with the correct element that I want to target. Great. Then when I try to get access to that element explicitly, it tells me it's undefined and that there is no element there. Any reason why this is happening?

Wesley
  • 1,217
  • 3
  • 12
  • 16
  • Java doesn't use ``const``. Are you using JavaScript rather than Java? They are very different languages, and I assume you know which one you're programming in. – NomadMaker Apr 02 '21 at 05:53
  • I'm using JavaScript. It's in the tags for this question – Wesley Apr 02 '21 at 05:57
  • Until @Lone_Coder edited the question, you were using the java rather than javascript tag. – NomadMaker Apr 02 '21 at 05:58
  • 1
    it's because it (`myVar`) is a HTML collection looks similar as an array but not an array , so to make it array use spread operator like `const arr = [..myVar]` then log as `arr[0]` – KcH Apr 02 '21 at 06:02

2 Answers2

1

Mozilla Docs seems to recommend HTMLCollection.item() to access the nodes. Additionally it will return null instead of undefined if the index is out of bounds so you may be able to locate the issue more easily.

Mozzdy
  • 51
  • 1
  • Still returns null when I do `console.log(myVar.item(0));` – Wesley Apr 02 '21 at 06:46
  • Is it possible that you made a typo in the class name? Check the HTMLCollection.length to make sure your not getting a null array. – Mozzdy Apr 02 '21 at 07:14
0

It seems to me that the class name is misspelled. If you look at the first output, you can see the number '0' which suggests that either the element does not exist or the class name is not spelled correctly. Try double checking to see if you got it right.