closest Finds Typed Ancestor Elements
closest walks the ancestor chain to the first matching selector, and its generic form hands back the concrete element class for dataset access.
Code
const button = document.querySelector<HTMLElement>('#save');
if (!button) {
console.log('button not found');
} else {
// closest 沿祖先链(ancestor chain)找第一个匹配 .card 的元素
const card = button.closest<HTMLElement>('.card');
if (card) {
// 泛型收窄成 HTMLElement:dataset 等专属属性直接可用
console.log('card id:', card.dataset.cardId ?? 'none');
console.log('button inside card:', card.contains(button));
} else {
console.log('no .card ancestor');
}
}How the snippet works
Top-level bindings button hold the demo state — nothing sits inside a function scope.
What to watch for
- The snippet leans on
document— browser-only surfaces a bare Node process cannot provide.
Using it
Look for the button not found, card id:, button inside card: prefixes when the file runs; they tie each line to its step.
Key statements
const button = document.querySelector<HTMLElement>('#save');
const card = button.closest<HTMLElement>('.card');
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- Does closest Finds Typed Ancestor Elements run in plain Node.js?
- No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.