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 trialNeil McPartlin
14,662 PointsHow 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.
1 Answer
Steven Parker
231,268 PointsYou 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.
Neil McPartlin
14,662 PointsNeil McPartlin
14,662 PointsThanks Steven. I had hoped that 'listUl.firstElementChild' was the actual constant but as you say, it's only the initial underlying 'value' that gets remembered. So with a list table like this which will grow and its order will change, there seems no point in declaring this constant and instead it seems safer to use...
I note that other students had run into this problem too. Thanks again.