azl397985856 / fe-interview

宇宙最强的前端面试指南 (https://lucifer.ren/fe-interview)
Apache License 2.0
2.84k stars 260 forks source link

【每日一题】– 2019-09-11 - 实现querySelector #33

Closed azl397985856 closed 5 years ago

azl397985856 commented 5 years ago

相信大家都用过Element.querySelector(selector)或者document.querySelector(selector) 来查找DOM元素,那么如何实现一个这样的一个函数,这个函数接受两个参数,分别为selector和element(默认为body),找到element所有子元素中满足selector的第一个元素。

// 实现querySelector
function querySelector(selector, element) {}
azl397985856 commented 5 years ago

这是一个考察递归的题目, 但是需要考虑的内容又、有很多。 比如selector支持什么? 你可能知道又id,class,元素,以及一些级联选择器,如果想要完整实现还是需要一定的代码量和心思缜密程度的。 这一点一定要在开始做之前想到。

为了简单起见,我这里只实现了class选择器,剩下的交给读者来完善。 JS代码:

function matchSelector(selector, element) {
  if (Array.prototype.includes.call(element.classList, selector.slice(1))) return true;
  return false;
}
function querySelector(selector, element) {
  if (element === null) return null;
  const children = element.children;
  let res = null;
  for(let child of children) {
    if (matchSelector(selector, child)) return child;
    res = querySelector(selector, child);
    if (res !== null) return res;
  }
  return null;
}

querySelector('.test', document.body);