Piano Keys Project getElementByID()


#1

Hi,

I am confused about the first lines of the code in the main.js file of the Piano Keys project.

Here is the link: https://www.codecademy.com/courses/build-interactive-websites/projects/piano-keys

Lines 2 - 6:

const keys = ['c-key', 'd-key', 'e-key', 'f-key', 'g-key', 'a-key', 'b-key', 'high-c-key', 'c-sharp-key', 'd-sharp-key', 'f-sharp-key', 'g-sharp-key', 'a-sharp-key'];
const notes = [];
keys.forEach(function(key){
  notes.push(document.getElementById(key));
})

In the index.html file of the Piano Keys project I can find a class named ‘key’ but not an id named ‘key’. I thought that the getElementById() method returns the element that has the ID attribute with the specified value.

Where do we define the id ‘key’ and why is it written without quotations in the main.js? Thank you very much for your help.


#2

If you are referring to the forEach loop on keys, then notice that key is not in quotes, as would be an named id in the source code. It is a local variable of the callback function as the loop iterates over the array of key id’s.

keys.forEach(function(key){
notes.push(document.getElementById(key));
});


#3

Got it, thank you very much!