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.

JavaScript JavaScript and the DOM (Retiring) Traversing the DOM Getting the First and Last Child

Neil McPartlin
Neil McPartlin
14,662 Points

How to get the global variable 'firstListItem' to work within functions?

I have managed to complete the task set by Guil...

https://w.trhou.se/uujm73kn3j

...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
Steven Parker
221,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.

Neil McPartlin
Neil McPartlin
14,662 Points

Thanks 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...

//const firstListItem = listUl.firstElementChild;
listUl.firstElementChild.style.backgroundColor = "green";

I note that other students had run into this problem too. Thanks again.