最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Implementing getElementsByClassName using Recursion - Stack Overflow

programmeradmin6浏览0评论

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);
      }
  }
发布评论

评论列表(0)

  1. 暂无评论