Categories
interview

DFS DOM (ES6)

<div id="root">
  <div>
    <ul>
      <li>1</li>
      <li>2</li>
      <li>3</li>
    </ul>
  </div>
  <div>
    <ul>
      <li>1</li>
      <li>2</li>
      <li>3</li>
    </ul>
  </div>
</div>
const root = document.getElementById('root');

const dfs = function(root, ret = []) {
  let obj = root.children;
  for (const val of root.children) {
    if (val.textContent === '1') {
      ret.push(val.tagName.toLowerCase());
    } else {
      dfs(val, ret);
    }
  }
  return ret;
};

console.log(dfs(root));
// ['li', 'li']

Demo