Skip to content

Latest commit

 

History

History
22 lines (18 loc) · 703 Bytes

匹配元素.md

File metadata and controls

22 lines (18 loc) · 703 Bytes

匹配元素

查找元素的所有祖先,直到元素与指定的选择器匹配为止。

  • 使用 Node.parentNodewhile 循环向上移动元素的祖先树。
  • 使用 Array.prototype.unshift() 将每个新祖先添加到数组的开头。
  • 使用 Element.matches() 检查当前元素是否与指定的选择器匹配。
const getParentsUntil = (el, selector) => {
  let parents = [],
    _el = el.parentNode
  while (_el && typeof _el.matches === 'function') {
    parents.unshift(_el)
    if (_el.matches(selector)) return parents
    else _el = _el.parentNode
  }
  return []
}

getParentsUntil(document.querySelector('#home-link'), 'header') // [header, nav, ul, li]