Skip to content
Advertisement

How to loop over document.body in a function

I have to write a version of getElementsByClassName but i’m having trouble using document.body in my function. It only returns null when called. I realize that the recursion part needs to be fixed and finished but first I’d like to know how to access document.body (along with its childNodes) and use it in a function. Or maybe I’m approaching it the wrong way?

var getElementsByClassName = function() {

  var bod = document.body;

  
  for (var i = 0; i < bod.childNodes.length; i++) {
    var thisNode = bod.childNodes[i];
    var classTest = bod.childNodes[i].className;
    if (classTest === classname) {
    }
    //recursion here
    if (thisNode.childNodes.length > 0) {
      getElementsByClassName();
    }
  }

};

Advertisement

Answer

Give the getElementsByClassName() function an argument of element and pass in each node that you want to recurse. Note that you can also use querySelectorAll() instead of writing your own.

var getElementsByClassName = function (element) {
  for (var i = 0; i < element.childNodes.length; i++) {
    var thisNode = element.childNodes[i];
    var classTest = thisNode.className;
    if (classTest === classname) {
    }
    //recursion here
    if (thisNode.childNodes.length > 0) {
      getElementsByClassName(thisNode);
    }
  }
};

getElementsByClassName(document.body);

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement