AniUI Academy
hard+350 XPPractice

Match a compound selector against a tree

Writing this once demystifies querySelectorAll completely. There are two halves: turning a selector string into a structure, and testing that structure against a node.

A node is a plain object { tag, attrs, children }, where attrs and children may be missing and a child may be a plain string of text. Implement matchAll(root, selector) returning an array of the matching **nodes** in document order — that is, depth-first pre-order, with the root itself as a candidate. String children are text and never match.

The selector is a single compound selector with no combinators: an optional leading tag name followed by any number of #id, .class and attribute parts. A node matches only when every part matches.

Tag names are compared case-insensitively, so div matches a node whose tag is "DIV". An #id part matches when attrs.id is exactly equal. A .class part treats attrs.class as a whitespace-separated list and requires the class as a whole token, so .item does not match class="itemized". Attribute parts are [attr] for presence with any value, and [attr="v"], [attr^="v"], [attr$="v"] and [attr*="v"] for exact, prefix, suffix and substring comparison against String(attrs[attr]); the value may be wrapped in double quotes, single quotes, or neither. Return an empty array when nothing matches.

What it has to do

  • Return matching nodes in depth-first pre-order, including the root when it matches.
  • Require every part of the compound selector to match.
  • Compare tag names case-insensitively and match classes as whole whitespace-separated tokens.
  • Support [attr], [attr="v"], [attr^="v"], [attr$="v"] and [attr*="v"], with optional quotes.
  • Skip string children and tolerate missing attrs or children, returning [] when nothing matches.

Your workspace

Try it yourself
Loading playground...

Ready to check it?

5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.

AI Crack & Solution Assist

Stuck? Get instant AI hints or break down the optimal solution.

Stuck? The javascript course covers everything this challenge needs.