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

Johann-S's avatar
Johann-S committed
8
import { find as findFn, findOne } from './polyfill'
9
import { makeArray } from '../util/index'
10

11
12
13
14
15
/**
 * ------------------------------------------------------------------------
 * Constants
 * ------------------------------------------------------------------------
 */
Johann-S's avatar
Johann-S committed
16

17
const NODE_TEXT = 3
Johann-S's avatar
Johann-S committed
18

19
20
const SelectorEngine = {
  matches(element, selector) {
Johann-S's avatar
Johann-S committed
21
    return element.matches(selector)
22
  },
Johann-S's avatar
Johann-S committed
23

24
  find(selector, element = document.documentElement) {
25
    return findFn.call(element, selector)
26
27
28
29
30
  },

  findOne(selector, element = document.documentElement) {
    return findOne.call(element, selector)
  },
Johann-S's avatar
Johann-S committed
31

32
  children(element, selector) {
33
    const children = makeArray(element.children)
34

XhmikosR's avatar
XhmikosR committed
35
    return children.filter(child => this.matches(child, selector))
36
  },
37

38
39
  parents(element, selector) {
    const parents = []
40

41
    let ancestor = element.parentNode
42
43

    while (ancestor && ancestor.nodeType === Node.ELEMENT_NODE && ancestor.nodeType !== NODE_TEXT) {
44
45
      if (this.matches(ancestor, selector)) {
        parents.push(ancestor)
46
47
      }

48
49
      ancestor = ancestor.parentNode
    }
50

51
52
    return parents
  },
53

54
  closest(element, selector) {
Johann-S's avatar
Johann-S committed
55
    return element.closest(selector)
56
  },
57

58
  prev(element, selector) {
59
    let previous = element.previousElementSibling
60

61
    while (previous) {
62
      if (this.matches(previous, selector)) {
63
        return [previous]
64
65
      }

66
      previous = previous.previousElementSibling
Johann-S's avatar
Johann-S committed
67
    }
68

69
70
71
72
73
74
75
76
77
78
79
80
81
82
    return []
  },

  next(element, selector) {
    let next = element.nextElementSibling

    while (next) {
      if (this.matches(next, selector)) {
        return [next]
      }

      next = next.nextElementSibling
    }

83
    return []
Johann-S's avatar
Johann-S committed
84
  }
85
}
Johann-S's avatar
Johann-S committed
86
87

export default SelectorEngine