DEV Community

kailashjakhar767
kailashjakhar767

Posted on

Polyfill for GetElementsByClassName

document.findByClass = function (requiredClass) {
  const body = this.body;
  function searchClasses(node) {
    let classes = [];
    let classList = node.classList || null;
    if (classList && classList.contains(requiredClass)) {
      classes.push(node);
    }

    let children = node.children;
    if (children.length > 0) {
      for (const element of children) {
        classes = classes.concat(searchClasses(element));
      }
    }
    return classes;
  }
  return searchClasses(body);
};

Enter fullscreen mode Exit fullscreen mode

Discussion (0)