My Name
My Name

Reputation: 155

Implementing getElementsByClassName using Recursion

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

Upvotes: 2

Views: 8566

Answers (3)

Dennis Khan
Dennis Khan

Reputation: 61

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

Upvotes: 2

ppoliani
ppoliani

Reputation: 4906

You are making some small when checking the className.

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

http://jsfiddle.net/us5xjv66/8/

Upvotes: 3

juvian
juvian

Reputation: 16068

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

Upvotes: 0

Related Questions