Skip to the solution
HardLow-Level DesignAsked in 20246 min read

DOM select elements custom selector

4.0k views

The problem

Problem, as an interviewer would state it: "Implement a minimal querySelectorAll-style engine from scratch — supporting a tag name, .class, #id, and a descendant combinator (space-separated compound selectors like .box .label)."

Examples:

Code
customQuerySelectorAll(document.body, ".box .label");
// every real element matching .label, nested anywhere inside an element matching .box

Clarifying questions expected:

  • Does a compound selector need to support combining a tag, class, AND id together (like div.box#unique), or just one selector type at a time?
  • Should results be returned in real DOCUMENT order, matching the native method?
  • Is only the descendant combinator (a space) in scope, or also child (>)/sibling (+/~) combinators?

Code / implementation expected: Yes — real, direct proof against the ACTUAL native querySelectorAll, on the identical real jsdom tree, for a class selector, a descendant-combinator selector, and an id selector.

  • js-coding
  • utility
  • algorithm

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: the custom selector engine matches the real, native querySelectorAll exactly, for a class selector, a descendant combinator, and an id selector

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 127 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextHard

Microtask scheduler task runner

Continue