Skip to content

Latest commit

Β 

History

History
60 lines (41 loc) Β· 1.65 KB

better-dom-traversing.md

File metadata and controls

60 lines (41 loc) Β· 1.65 KB

better-dom-traversing

πŸ“ Prefer better DOM traversal APIs.

πŸ’Ό This rule is enabled in the following configs: βœ… recommended, β˜‘οΈ unopinionated.

πŸ’‘ This rule is manually fixable by editor suggestions.

Prefer more readable and robust DOM traversal APIs.

Use named first-child properties instead of positional access, selectors instead of positional child traversal, .closest() instead of repeated parent traversal, and merged .querySelector() calls when static selectors can be combined.

This rule is syntax-based and reports common DOM traversal patterns. Suggestions are intentionally manual because the replacement can change behavior in some cases, such as undefined versus null for empty child collections, exact-depth parent traversal versus selector-based ancestor lookup, or chained querySelector() calls that only search inside the first matching element.

props.children access is ignored because it is component data, not DOM traversal.

Examples

// ❌
element.childNodes[0];

// βœ…
element.firstChild;
// ❌
element.children[0];

// βœ…
element.firstElementChild;
// ❌
element.children[2];

// βœ…
element.querySelector(':scope selector');
// ❌
element.parentElement.parentElement;

// βœ…
element.closest('selector');
// ❌
element.querySelector('a').querySelector('b');

// βœ…
element.querySelector(':scope a b');