0
0
mirror of https://github.com/twbs/bootstrap.git synced 2025-02-08 05:54:23 +01:00
Bootstrap/js/src/dom/selector-engine.js

74 lines
1.7 KiB
JavaScript
Raw Normal View History

2017-08-21 09:11:37 +02:00
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.3.1): dom/selector-engine.js
2017-08-21 09:11:37 +02:00
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
2019-03-16 16:10:23 +02:00
import { find as findFn, findOne, matches, closest } from './polyfill'
import { makeArray } from '../util/index'
2018-09-14 14:27:30 +02:00
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
2017-08-26 12:44:26 +02:00
const NODE_TEXT = 3
2017-08-26 12:44:26 +02:00
2018-09-14 14:27:30 +02:00
const SelectorEngine = {
matches(element, selector) {
2019-03-16 16:10:23 +02:00
return matches.call(element, selector)
2018-09-14 14:27:30 +02:00
},
2017-09-20 14:19:10 +02:00
2018-09-14 14:27:30 +02:00
find(selector, element = document.documentElement) {
return findFn.call(element, selector)
2018-09-14 14:27:30 +02:00
},
findOne(selector, element = document.documentElement) {
return findOne.call(element, selector)
},
2017-09-20 14:19:10 +02:00
2018-09-14 14:27:30 +02:00
children(element, selector) {
const children = makeArray(element.children)
2019-02-26 13:20:34 +02:00
return children.filter(child => this.matches(child, selector))
2018-09-14 14:27:30 +02:00
},
2017-09-25 09:09:01 +02:00
2018-09-14 14:27:30 +02:00
parents(element, selector) {
const parents = []
2019-03-24 18:30:30 +01:00
2018-09-14 14:27:30 +02:00
let ancestor = element.parentNode
while (ancestor && ancestor.nodeType === Node.ELEMENT_NODE && ancestor.nodeType !== NODE_TEXT) {
2018-09-14 14:27:30 +02:00
if (this.matches(ancestor, selector)) {
parents.push(ancestor)
2017-09-25 09:09:01 +02:00
}
2018-09-14 14:27:30 +02:00
ancestor = ancestor.parentNode
}
2017-09-25 09:09:01 +02:00
2018-09-14 14:27:30 +02:00
return parents
},
2018-09-14 14:27:30 +02:00
closest(element, selector) {
2019-03-16 16:10:23 +02:00
return closest.call(element, selector)
2018-09-14 14:27:30 +02:00
},
2017-09-25 09:09:01 +02:00
2018-09-14 14:27:30 +02:00
prev(element, selector) {
let previous = element.previousElementSibling
2019-03-24 18:30:30 +01:00
while (previous) {
2018-09-14 14:27:30 +02:00
if (this.matches(previous, selector)) {
return [previous]
2017-09-25 09:09:01 +02:00
}
previous = previous.previousElementSibling
2017-09-20 14:19:10 +02:00
}
2018-09-14 14:27:30 +02:00
return []
2017-08-21 09:11:37 +02:00
}
2018-09-14 14:27:30 +02:00
}
2017-08-21 09:11:37 +02:00
export default SelectorEngine