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 trial
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 Parker229,005 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.