cielux
10/25/2018 - 10:13 PM

Get By Class Name

Get By Class Name return array of elements Get by Class Hierarchy return array of last elements in the hierarchy

const { JSDOM } = require("jsdom");
const { document } = new JSDOM(`
  <div id="root" class='a'>
      <div class='a' id='a-1'>
          <div class='a' id='a-2'>
               <div class='b' id='d-1'></div>  <--
          </div>
          <div class='c' id='c-1'>
              <div class='a' id='a-3'>
                   <div class='d' id='d-2'></div>  <--
              </div>
          </div>
      </div>
  </div>
`).window;
const getIds = (elements=[]) => Array.from(elements).map(x => x.id);
/*

className
classList
children

*/

function hasClass(element, className) {
  return Object.values(element.classList).includes(className);
}

function getChildrenWithClassName(element, className, results) {
  if(hasClass(element, className)) {
    results.push(element);
  }
  for(const child of element.children) {
    getChildrenWithClassName(child, className, results);
  }
}

function getChildrenWithHierarchy(element, hierarchyList, count, results) {
  if (hasClass(element, hierarchyList[count])) {
    console.log("hasClass", hierarchyList[count]);
    if (count === hierarchyList.length-1) {
      results.push(element);
      
    } else {
      count++;
    }
  } else {
    return;
  }
  
  for(const child of element.children) {
    getChildrenWithHierarchy(child, hierarchyList, count, results);
  }
}

function getByClassName(element, className) {
  let results = [];
  getChildrenWithClassName(element, className, results);
  
  return results;
}


const rootNode = document.getElementById('root');
// console.log("results", getIds(getByClassName(rootNode, 'a')));



function getByClassNameHierarchy(element, hierarchy) {
  const hierarchyList = hierarchy.split('>');
  let results = [];
  getChildrenWithHierarchy(element, hierarchyList, 0, results);
  return results;
}


console.log("results", getIds(getByClassNameHierarchy(rootNode, 'a>a')));
// a-1, a-2
// a>b>a>b
// 
// console.log("results", getIds(getByClassNameHierarchy(rootNode, 'a>b>a>d')));