Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.
Neil McPartlin14,662 Points
How to get the global variable 'firstListItem' to work within functions?
I have managed to complete the task set by Guil...
...but I am unable to re-use the 2 constants created by Guil in his video in my functions.
const firstListItem = listUl.firstElementChild; const lastListItem = listUl.lastElementChild;
During the initial load of the program, all is well, but as soon as the UP or DOWN buttons (functions) are used, both firstListItem and lastListItem do not update. My workaround is to simply use listUl.firstElementChild and listUl.lastElementChild in their stead.
Could someone please explain why this is so, and suggest a solution. (I do know my code needs a lot of refactoring, but I'm trying understand why this specifically does not work).
Thanks in advance.
Steven Parker221,070 Points
You say "both firstListItem and lastListItem do not update"; but since they are both constants, they should not be expected to change. Each is permanently associated with the element that occupied the corresponding position initially, and that association will not change when the element is moved.
It sounds like you've already discovered the solution, by sampling listUl.firstElementChild and listUl.lastElementChild again whenever you need to identify or access the elements currently in those positions.