Finding and walking nodes in JavaScript
The query methods, and moving between related elements.
function inspect() {
const rows = document.querySelectorAll(".step");
const locked = [...rows].filter((row) => row.matches("[data-locked]"));
const first = rows[0];
const tour = first?.closest("[data-tour]")?.dataset.tour;
return {
total: rows.length,
locked: locked.length,
tour,
next: first?.nextElementSibling?.textContent?.trim(),
parentTag: first?.parentElement?.tagName,
};
}
How it works
querySelectorAllreturns a static NodeList, not an array.closestwalks up;childrenandmatchesdo the rest.- Spread the NodeList when you want array methods.
Keywords and builtins used here
constdocumentfunctionreturn
The run, in numbers
- Lines
- 15
- Characters to type
- 383
- Tokens
- 105
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 66 seconds.
Step 3 of 3 in The DOM, step 3 of 13 in The browser.