简体   繁体   中英

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

};

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM