1

I'm trying to get all elements of a class name into an array so that I can map over them and add a new class. The issue I have is when I run the following in my code editor:

var a = document.getElementsByClassName('commissioner-profile-container');

and try to turn the array-like object it returns into an array by then running:

var b = Array.prototype.slice.call(a, 0);

var a will print to the console as the array-like object, but var b prints as simply an empty array.

However, when I do run both of these straight into the console with the page open, they work:

enter image description here

Any idea as to why this is?

hidace
  • 3,969
  • 6
  • 36
  • 61
  • what about console.log(a.length, b.length) from your editor? Are you sure the b declaration is using the expected a variable (no redefinition in between, etc)? – floribon Mar 29 '16 at 14:06
  • 2
    Where in the page are you embedding this code? If it is at the top, and not in an onload function, then it is being called before there are any commissioner-profile-container elements to find. – Tim Jasko Mar 29 '16 at 14:08
  • 1
    as Tim said. Put your ` – Roko C. Buljan Mar 29 '16 at 14:08
  • Thank you @TimJasko (and Roko). Thought I had it placed towards the bottom, but it was in the document head. Moved it to the bottom and it now works. Thanks! – hidace Mar 29 '16 at 14:11

0 Answers0