You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

递归实现getElementsByClassName的执行逻辑及代码优化疑问

Understanding the Recursive getElementsByClassName Function

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:

  1. Initialize an empty array: Every function call starts with var arr = []—this will hold matching elements from the current subtree.
  2. Check the current element: If the element is an HTML node (has classList) and contains the target className, add it to arr.
  3. Recurse through child nodes: Loop over all child nodes of the current element. For each child, call getElementsByClassName again with that child as the new root.
  4. Merge results: Each recursive call returns an array of matches from the child’s subtree. We merge this array into the current arr using concat().
  5. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 14:00:12