selectorEngine.js 1.06 KB
Newer Older
Johann-S's avatar
Johann-S committed
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
/**
 * --------------------------------------------------------------------------
 * Bootstrap (v4.0.0-beta): dom/selectorEngine.js
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * --------------------------------------------------------------------------
 */

const SelectorEngine = {
  matches: Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector,

  find(selector) {
    if (typeof selector !== 'string') {
      return null
    }

    let selectorType = 'querySelectorAll'
    if (selector.indexOf('#') === 0) {
      selectorType = 'getElementById'
      selector = selector.substr(1, selector.length)
    }
    return document[selectorType](selector)
  },

  closest(element, selector) {
    let ancestor = element
    if (!document.documentElement.contains(element)) {
      return null
    }

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

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

    return null
  }
}

export default SelectorEngine