Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialKeith Walker
5,076 PointsSelecting ID's with variables.
So I'm a bit confused as to what is happening when we call the elements from the html.
for instance
const myHeading = document.getElementById('myHeading');
now I assumed we were assigning the const variable myHeading to equal the element in the HTML with the ID of 'myHeading'. Then using this variable with the addEventListener method. Yet it doesn't seem to matter what the name of the const variable is. for instance I can say
const myHeadingIsSomethingElse = document.getElementById('myHeading');
and still use
myHeading.addEventListener();
What is the point of assigning the variables in this case? is it simply loading those elements to the JS? Do we actually call upon those variables anywhere else, or do we always use the id of the element from the html? Could you assign something else to that variable later in the code (considering you use let instead of const), and still have access to the the element?
1 Answer
Dario Bahena
10,697 PointsYou are probably using chrome or some variant. Chrome does some stuff automatically for convenience in development. If you go to the console and type myHeading, you will be able to access the dom node instantly. This is not javascript but hidden stuff in the chrome browser itself. Do not rely on it. It's just to help development. It will not work in Firefox or edge.
//
const whateverYouWantDoesntMatter = document.getElementById('myHeading');
// the dom item is now associated to the whateverYouWantDoesntMatter variable
// by definition, variable means it can be anything within the rules of naming in js.