Building getElementsByClassName() from Scratch in JavaScript
Ever wondered how to implement a native DOM method yourself? This frontend problem is a great way to practice DOM traversal, recursion, and class matching.
The Problem
Implement getElementsByClassName(element, classNames) to return all descendant elements that contain every requested class.
It should handle:
- Multiple class names, like "foo bar".
- Duplicate class names in the input.
- Extra whitespace in the input or HTML class attributes.
- Nested elements without returning duplicates.
The Approach
We can solve this using Depth-First Search (DFS).
- Split the requested class names by whitespace.
- Remove duplicates using a Set.
- Traverse the DOM tree recursively.
- Check whether each element contains every requested class.
- Add matching elements to the result.
Implementation
export default function getElementsByClassName(element, classNames) {
const result = [];
const classes = [
...new Set(classNames.trim().split(/\s+/).filter(Boolean)),
];
function solve(node) {
for (const child of node.children) {
if (classes.every((cls) => child.classList.contains(cls))) {
result.push(child);
}
solve(child);
}
}
solve(element);
return result;
}Key Insights
1. Why use classList.contains()?
It checks for an exact class token rather than a partial string match. For example, "foo" should not match "fooz".
2. Why use every()?
When the input is "foo bar", an element must contain both classes to qualify.
3. Why use a Set?
Duplicate requested classes, such as "foo foo", should not change the result.
4. Why use recursion?
Elements can be nested at any depth. Recursion lets us explore every descendant while preserving document order.
Complexity Analysis
Let n be the number of descendant elements and m the number of unique requested classes.
- Time: O(n × m) in the worst case.
- Space: O(m + h + k), where h is the DOM tree height and k is the number of matching elements.
Takeaway
This problem is more than a DOM exercise. It combines tree traversal, recursion, sets, and array methods in one practical frontend interview question.
Understanding these fundamentals makes implementing other DOM utilities much easier.
Building getElementsByClassName() from Scratch in JavaScript was originally published in Modern Frontend on Medium, where people are continuing the conversation by highlighting and responding to this story.