getElementsByClassName递归

时间:2015-12-29 05:21:46

标签: javascript function dom recursion polyfills

我一直在尝试实现一个与DOM方法完全相同的getElementsByClassName函数。通过大量的研究,我得出了以下内容,但似乎返回的内容与标准方法返回的内容不匹配。最后的console.log语句似乎打印出我要查找的内容,但不知何故返回的内容有所不同。任何建议或帮助将不胜感激!

var getElementsByClassName = function(className){
  var results= [];
  var bod = document.body;
    var iterateBod = function(bod){

    if(bod.classList && bod.classList.contains(className)){
        results.push(bod); 
        console.log(results)
    }else{
        for(var i = 0; i < bod.childNodes.length; i++){
            iterateBod(bod.childNodes[i]);
        }
    }
    };

iterateBod(bod);
console.log(results);
return results;
};

1 个答案:

答案 0 :(得分:0)

更改递归内的条件

var getElementsByClassName = function(className){
var results= [];
var bod = document.body;
  var iterateBod = function(bod){
    if(bod.classList && bod.classList.contains(className))
     {
     results.push(bod); 
     console.log(results);
     if(bod.childNodes)
     {
         for(var i = 0; i < bod.childNodes.length; i++)
         {
             iterateBod(bod.childNodes[i]);
         }
     }
   }
 };

iterateBod(bod);
console.log(results);
return results;
};