Skip to the solution
MediumFrontendAsked in 20246 min read

Custom getElementsByClassName traverse

1.7k views

The problem

Problem, as an interviewer would state it: "Implement a custom getElementsByClassName(root, className) from scratch, using a recursive tree traversal instead of the built-in DOM method."

Examples:

Code
customGetElementsByClassName(document.body, "box"); // an array of every descendant with class "box"

Clarifying questions expected:

  • Should this match an element with MULTIPLE classes, as long as one of them equals the target?
  • Depth-first or breadth-first traversal — does the order matter for a real use case?
  • Return a live-updating collection (like the real native method does) or a static snapshot array?

Code / implementation expected: Yes — real, direct proof against the REAL native getElementsByClassName, confirming identical results on a real nested DOM tree.

  • 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 recursive implementation matches the real, native getElementsByClassName exactly, on a real nested DOM tree

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 73 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 nextMedium

Validate a Binary Search Tree

Continue