selectorEngine.js 1.63 KB
Newer Older
Johann-S's avatar
Johann-S committed
1
2
3
4
5
6
7
/**
 * --------------------------------------------------------------------------
 * Bootstrap (v4.0.0-beta): dom/selectorEngine.js
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * --------------------------------------------------------------------------
 */

8
9
10
11
12
13
14
15
16
17
18
// matches polyfill (see: https://mzl.la/2ikXneG)
let fnMatches = null
if (!Element.prototype.matches) {
  fnMatches =
    Element.prototype.msMatchesSelector ||
    Element.prototype.webkitMatchesSelector
} else {
  fnMatches = Element.prototype.matches
}

// closest polyfill (see: https://mzl.la/2vXggaI)
19
let fnClosest = null
20
if (!Element.prototype.closest) {
21
  fnClosest = (element, selector) => {
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
    let ancestor = element
    if (!document.documentElement.contains(element)) {
      return null
    }

    do {
      if (fnMatches.call(ancestor, selector)) {
        return ancestor
      }

      ancestor = ancestor.parentElement
    } while (ancestor !== null)

    return null
  }
37
38
39
40
41
} else {
  // eslint-disable-next-line arrow-body-style
  fnClosest = (element, selector) => {
    return element.closest(selector)
  }
42
43
}

Johann-S's avatar
Johann-S committed
44
const SelectorEngine = {
45
46
47
  matches(element, selector) {
    return fnMatches.call(element, selector)
  },
Johann-S's avatar
Johann-S committed
48

49
  find(element = document, selector) {
Johann-S's avatar
Johann-S committed
50
51
52
53
54
55
56
57
58
    if (typeof selector !== 'string') {
      return null
    }

    let selectorType = 'querySelectorAll'
    if (selector.indexOf('#') === 0) {
      selectorType = 'getElementById'
      selector = selector.substr(1, selector.length)
    }
59
    return element[selectorType](selector)
Johann-S's avatar
Johann-S committed
60
61
62
  },

  closest(element, selector) {
63
    return fnClosest(element, selector)
Johann-S's avatar
Johann-S committed
64
65
66
67
  }
}

export default SelectorEngine