JavaScript JavaScript and the DOM Traversing the DOM Getting the First and Last Child

Peter Retvari
Peter Retvari
Full Stack JavaScript Techdegree Student 8,391 Points

My solution for the "button up and down remove challenge " ?

Hi folks,

I solved the challenge regarding to the button problem (e.g.: when the last child has a down button). Maybe my solution is too complicated, so if you have a shorter or more effective version and you could share it, it would be nice. Here is mine:

https://w.trhou.se/5k18weqrhd

The program works smoothly (you can add, delete/remove buttons and it's also responsive because when you have only 1 item left it shows only the remove button or if you have only 2 items left it shows only up for the list item and only down for the first),

BUT I don't understand these 2 variables:

const firstListitem = ulFater.firstElementChild;
const lastListitem = ulFater.lastElementChild;

After you run the program and remove some items/ add some items and call this variable in the console, you will see that the firstElementChild variable has remained "Grapes", however, if you type "ulFater" or "lis" variable in the console, you can say that these variables show the actual/current list.

Why is this? ulFater is correct but firstListitem variable is not updated? Could you please help?

2 Answers

Steven Parker
Steven Parker
171,296 Points

I assume your "ulFater" contains an HTMLCollection, and those are "live" which means they get updated when any changes are made in the DOM.

But when you take the value of one of their properties and put it into another variable (like "firstListitem") that value remains what it was at the moment of the assignment until/unless it is assigned again.

Peter Retvari
Peter Retvari
Full Stack JavaScript Techdegree Student 8,391 Points

Thank you, Steven, you're awesome as always ? I thought that only document.querySelectorAll is 'live', because of the Nodelist but not the simple querySelector. So all HTML collections are live?

Steven Parker
Steven Parker
171,296 Points

The HTMLCollections are live, but "querySelector" returns a single element not a collection.

Peter Retvari
Peter Retvari
Full Stack JavaScript Techdegree Student 8,391 Points

But ulFater comes from a simple querySelector:

const ulFater = document.querySelector('ul');
Steven Parker
Steven Parker
171,296 Points

Sorry, I misinterpreted the situation. But the concept is still similar. Since "ulFater" refers to the element itself, if you use it to access any properties, they will show the current state of that element.

But if you copy the value of a property to a variable, that variable will always show what the value was at the time of the assignment.