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.

TypescriptForm Validation

Code

typescriptsnippet
16 lines
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

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.