For AI agents: the complete documentation index is available at https://rslint.rs/llms.txt, the full documentation bundle is available at https://rslint.rs/llms-full.txt, and this page is available as Markdown at https://rslint.rs/rules/unicorn/better-dom-traversing.md.
close

better-dom-traversing

Unreleased

Configuration

rslint.config.ts
import { defineConfig, unicornPlugin } from '@rslint/core';

export default defineConfig([
  unicornPlugin.configs.recommended,
  {
    rules: {
      'unicorn/better-dom-traversing': 'error',
    },
  },
]);

Rule Details

Prefer .firstChild and .firstElementChild when reading the first child of a DOM node. The rule also reports later .children indexes, repeated .parentElement access, and chains of static .querySelector() calls. It ignores writes to child collections and component props.children reads.

Examples

Incorrect

element.childNodes[0];
element.children[0];
element.children[2];
element.parentElement.parentElement;
element.querySelector('a').querySelector('b');

Correct

element.firstChild;
element.firstElementChild;
element.querySelector(':scope selector');
element.closest('selector');
element.querySelector(':scope a b');

Suggestions

The rule offers editor suggestions for first-child access and for chains of static querySelector() calls with compatible selectors. First-child properties return null when empty, while an indexed access returns undefined. A combined selector can find matches outside the first element selected by the original chain.

Options

This rule has no options.

Differences from upstream

In compact code, rslint adds spaces when a suggestion removes brackets or parentheses next to a keyword. For example, the suggestion for element.children[0]in nodes produces element.firstElementChild in nodes. The space keeps the in expression valid.

Original Documentation