Skip to content

findUpElement

Functions

findUpElement()

findUpElement<T>(source, target, end?): T | null

自起始元素向上查找目标元素,父级元素不存在或终止条件成立时返回 null

Type parameters

Parameter
T extends Element

Parameters

ParameterTypeDescription
sourceMaybeNullish<Element>起始元素
targetMaybeNullish<T | (el) => boolean | void>目标元素
end?MaybeNullish<Element | (el) => boolean | void>终止条件

Returns

T | null

查找到的目标元素

Example

ts
const containerElement = document.querySelector('.button-container')
// 事件委托
containerElement.addEventListener('click', handleMouseClick, { capture: true })

function handleMouseClick(e) {
  // 自事件触发元素向上查找目标按钮元素,直到容器元素终止
  const target = findUpElement(e.target, (el) => el.classList.contains('.btn'), containerElement)
  if (target) {
    console.log(target)
  }
}