-
Notifications
You must be signed in to change notification settings - Fork 0
/
closest.js
42 lines (36 loc) · 1.12 KB
/
closest.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import matches from './matches'
import getParentOrHost from './getParentOrHost'
/**
* 获取 options 元素父元素最近的包含 selector 选择器的元素
* ========================================================================
* @method closest
* @param {HTMLElement} el - (必须)DOM 元素
* @param {String} selector - (必须)DOM 元素的选择其
* @param {HTMLElement} [ctx] - (必须)比对的 DOM 元素
* @param {Boolean} [includeCTX] - (必须)是否包含 context DOM 元素
* @returns {null|HTMLElement} - 返回最接近的 DOM 元素
*/
const closest = (el, selector, ctx, includeCTX) => {
const context = ctx || document
if (!el) {
return null
}
do {
/* istanbul ignore else */
if (
(selector != null &&
(selector[0] === '>'
? el.parentNode === context && matches(el, selector)
: matches(el, selector))) ||
(includeCTX && el === context)
) {
return el
}
/* istanbul ignore else */
if (el === context) {
break
}
/* jshint boss:true */
} while ((el = getParentOrHost(el)))
}
export default closest