递归实现getElementsByClassName的执行逻辑及代码优化疑问
Let’s break down how this code works, then answer your questions about the recursion flow and variable usage.
Core Flow of the Recursion
This function traverses the DOM tree recursively to collect every element matching the target class name. Here’s a step-by-step breakdown:
- Initialize an empty array: Every function call starts with
var arr = []—this will hold matching elements from the current subtree. - Check the current element: If the element is an HTML node (has
classList) and contains the targetclassName, add it toarr. - Recurse through child nodes: Loop over all child nodes of the current element. For each child, call
getElementsByClassNameagain with that child as the new root. - Merge results: Each recursive call returns an array of matches from the child’s subtree. We merge this array into the current
arrusingconcat(). - Return the final array: After processing all children, return
arr—it includes the current element (if it matched) plus all matches from its entire subtree.
Why Can We Concatenate res with arr?
Every recursive call to getElementsByClassName returns an array—even if no matches were found in that subtree, it returns an empty array.
The res variable is just a temporary holder for the recursive result. Since both arr and res are arrays, concat() works perfectly to merge them: it appends all elements from res to arr, creating a combined array that we assign back to arr.
For example: if the current element doesn’t match the class but one of its children returns an array with two matches, arr starts empty, then concat(res) adds those two elements to it.
Can We Remove the res Variable?
Absolutely. You can rewrite the line to:
arr = arr.concat(getElementsByClassName(className, element.childNodes[i]))
This does exactly the same thing as storing the recursive result in res first. The res variable is just a readability convenience—some developers prefer breaking operations into separate steps, but it’s not functionally required. Both versions produce identical results.
Quick Note on childNodes
element.childNodes includes all node types (text nodes, comment nodes, etc.), not just HTML elements. That’s why we check if (element.classList)—it ensures we only attempt to check the class list on valid elements, avoiding errors on nodes without a classList property.
内容的提问来源于stack exchange,提问作者yesser labidi

