admin管理员组

文章数量:1327688

I created a function within getElementsByClassName that tests the current node to check if it matches the className, then recursively tests the childNodes of the current node.

To me, this logically make sense, but I'm not sure why the results don't produce identical results as getElementsByClassName. I tried implementing a for loop that checks every node in the current level, but that doesn't seem to be working either. What do I need to adjust in the first if statement to get this code working?

function getElementsByClassName (className) {
  var nodeList = [];
  function test(node) {
      if (node.classList === className) {
        nodeList.push(node.classList[count]);
      }
    for (var index = 0; index < node.childNodes.length; index++) {
      test(node.childNodes[index]);
    }
  }
  test(document.body)
  return nodeList;
};

I created a function within getElementsByClassName that tests the current node to check if it matches the className, then recursively tests the childNodes of the current node.

To me, this logically make sense, but I'm not sure why the results don't produce identical results as getElementsByClassName. I tried implementing a for loop that checks every node in the current level, but that doesn't seem to be working either. What do I need to adjust in the first if statement to get this code working?

function getElementsByClassName (className) {
  var nodeList = [];
  function test(node) {
      if (node.classList === className) {
        nodeList.push(node.classList[count]);
      }
    for (var index = 0; index < node.childNodes.length; index++) {
      test(node.childNodes[index]);
    }
  }
  test(document.body)
  return nodeList;
};
Share Improve this question asked Mar 12, 2015 at 15:33 My NameMy Name 1552 silver badges15 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

You are making some small when checking the className.

if (node.classList && node.classList.contains(className)) {
    nodeList.push(node);
}

http://jsfiddle/us5xjv66/8/

Working solution using underscore.js:

function getElementsByClassName(className) {
  var nodeList = [];
  function test(node) {
    if (_(node.classList).contains(className)) {
      nodeList.push(node);
    }
    _(node.childNodes).forEach(function(child) {
      test(child);
    });
  }
  test(document.body);
  return nodeList;
}

I think this is what you are trying to achieve:

  if (node.className  === className) { // if classname matches, add node to list
    nodeList.push(node);
  }

Or better yet, to handle multiple classnames:

  if(node.classList){
      if (node.classList.contains(className)) {
        nodeList.push(node);
      }
  }

本文标签: javascriptImplementing getElementsByClassName using RecursionStack Overflow