In this video, you started from Jonas’s Check in button and stepped through the page’s tree to the elements around it, then gave the Check in handler the same step up to its guest’s list item.
Key Points
- Suppose all you hold is a Check in button. To change a guest’s whole row later, the code has to reach the list item around the button.
- Each player’s list item is a child of the players list, and it has two children of its own: the
spanwith the name, and the button. - Every element knows where it sits in the tree.
parentElementis the element directly around it, sojonasButton.parentElementis Jonas’s list item. childrenis a list of the elements directly inside an element, in page order. This list is anHTMLCollection. Like a NodeList, it has alengthand positions, andfor...ofworks on it, but it has noforEach().firstElementChildgives only the first of them. On Jonas’s item, that’s thespan, and itstextContentis'Jonas'.- Watch out for
firstChildandchildNodes, without Element in their names: they count the text between tags as well. Jonas’s item, built withcreateElement()andappend(), has none. But inindex.html, the line break before the first heading inmainis text, so afterconst main = document.querySelector("main");,main.firstChildis that text, not the heading.main.firstElementChildis the heading. nextElementSiblingsteps across to the next element with the same parent. From Jonas’sspan, that’s his button.- Each
parentElementis one step up, sojonasButton.parentElement.parentElementis the players list,<ul id="players">. - Counting steps depends on the exact HTML.
closest()takes a CSS selector, checks the element itself, then its parent, then each one further up, and returns the first match.jonasButton.closest("li")is Jonas’s list item. If nothing matches,nullcomes back. - From an element you hold,
parentElementandclosest()step up,childrenandfirstElementChildstep down, andnextElementSiblingsteps across.
The Final Code
Here’s drawPlayers() in scratch/main.js after this video. Only the Check in arrow’s body changed: