fix(pseudos): match parentless elements for :nth-*(n)

BA
9d ago
+36-5

Fixes #1945

When the :nth-* formula matches every index (n, n+0, +n, ...), compileNth took a shortcut that also required the element to have a parent element. So elements without one (the root <html>, detached elements, top-level nodes of a parsed fragment) failed :nth-child(n), while :nth-child(1), :nth-child(n+1) and :first-child matched them. Selectors 4 lets these pseudo-classes match elements without a parent, and Chrome matches <html> for :nth-child(n).

The shortcut now just returns next.

Tests in test/pseudo-classes.ts, for all four :nth-* pseudo-classes:

  • a detached element matches (1), (n) and (-n+3)
  • in <html><head></head><body></body></html>, (n) and (n+0) select the same elements as *
  • top-level elements of <p></p><span></span><p></p> match :nth-child(n) / :nth-of-type(n)

The 9 new tests fail without the fix. npm test (vitest + lint) passes.

I found this with a differential test against headless Chrome (random trees and selectors). Apart from nested :has() and :dir(), it was the only mismatch in 9000 cases.

Summary by CodeRabbit

  • Bug Fixes
    • Updated nth-child and related selectors so formulas that match every index also match detached elements and elements at the root or top level of a fragment.