Search code examples
javascriptfunctiondomrecursionpolyfills

getElementsByClassName recursion


I have been trying to implement a getElementsByClassName function that behaves exactly like the DOM method. Through much research I have come up with the following but it seems that what is returned does not match what the standard method will return. The last console.log statement appears to print what I am looking for but somehow what is returned differs. Any suggestions or help would be greatly appreciated!

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;
};

Solution

  • change the condition inside recursion

    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;
    };