0

I've been working on some code with a collection of elements, while encountering some seemingly broken results. It appears to have the elements I need (as show on the output), but when I try to index one, it returns undefined.

var items = document.getElementsByClassName('side-item');
console.log(items);
console.log(items[0]);
console.log(items);

The resulting Console output:

The resulting Console output

I'd appreciate some help

Alon Eitan
  • 11,997
  • 8
  • 49
  • 58
Richard Nagy
  • 141
  • 9
  • 1
    Welcome to SO. Please add the __code__ to your question, not as links to images somewhere off-site. – Andy Dec 08 '18 at 14:19
  • 1
    Most of the questions here contain *some code*, some of them work *on a collection* and all of them get some *interesting result / error*. Please describe *your* case, whats working, whats not, what are you trying to achieve? – Jonas Wilms Dec 08 '18 at 14:22
  • 1
    you are looking for [this](https://stackoverflow.com/questions/23392111/console-log-async-or-sync) by the way – Jonas Wilms Dec 08 '18 at 14:27
  • No, I am not. I'm interested in why the element is undefined – Richard Nagy Dec 08 '18 at 14:39
  • What happens if you do `console.log(items.length);` first? – melpomene Dec 08 '18 at 14:45
  • It returns 0, while the length should be 3 apparently – Richard Nagy Dec 08 '18 at 14:46
  • No, your `items` is empty. It appears to be filled later on because `console.log` is async in your browser, as explained in Jonas' link. – melpomene Dec 08 '18 at 14:48
  • Ah I see. But why is it empty? It clearly has to be filled up by that call. Unless it is async, but I'm not sure why that would be. :I – Richard Nagy Dec 08 '18 at 14:51
  • 1
    Something else must be going on as [your code does not reproduce your problem](http://jsfiddle.net/ufh5ncmy/) – James Dec 08 '18 at 14:51
  • @RichárdNagy I'm guessing by the time your code runs, there are no elements with class `side-item` yet. They're probably created later. – melpomene Dec 08 '18 at 14:55
  • Unfortunately I cannot reproduce it in JSFiddle either. I copied the whole documents (html and css) there :I – Richard Nagy Dec 08 '18 at 14:57
  • Just curious, but what happens if you do console.log(document.getElementsByClassName('side-item')[0]) ? – Doug F Dec 08 '18 at 15:08
  • Here's a reproducer: http://jsfiddle.net/smco60z9/1/ – melpomene Dec 08 '18 at 17:23

0 Answers0