Marcus
Marcus

Reputation: 53

getElementsByClassName from scratch with recursion

My code doesn't work and I don't know why.

var getElementsByClassName = function(className){
  let result = [];
  let child = document.body.childNodes;
  function nodeRecusion(node) {
    for (let i = 0; i < node.length; i++) {
      let current = node[i];
      if (current.classList.contains(className)) {
      result.push(node[i]);
      }
      if (current.childNodes.length) {
      nodeRecusion(current);
      }
    }
  }
  nodeRecusion(child);
  return result;
};

The error I'm getting is 'cannot read property .contains of undefined'. I don't understand the issue though. Is it not receiving child properly or is the problem with how I'm trying to call it recursively?

Upvotes: 0

Views: 615

Answers (2)

Ele
Ele

Reputation: 33726

The classList attribute is available for Element class and not for Node interface.

You can use document.body.children instead.

var getElementsByClassName = function(className) {
  let result = [];
  let child = document.body.children;

  function nodeRecusion(node) {
    for (let i = 0; i < node.length; i++) {
      let current = node[i];
      if (current.classList.contains(className)) {
        result.push(node[i]);
      }
      if (current.children.length) {
        nodeRecusion(current);
      }
    }
  }
  
  nodeRecusion(child);
  return result;
};

console.log(getElementsByClassName('ele'));
<p class='ele'></p>
<span class='ele'></span>
<span class='stack'></span>

Upvotes: 3

LFR502
LFR502

Reputation: 56

Try replacing it in the third line

let child = document.body.children;

Upvotes: 0

Related Questions