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

97 lines
2.2 KiB
JavaScript
Raw Normal View History

import Polyfill from './polyfill'
2017-09-26 10:04:31 +02:00
import Util from '../util'
2017-08-21 09:11:37 +02:00
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.0.0-beta): dom/selectorEngine.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
2017-09-20 14:19:10 +02:00
const SelectorEngine = (() => {
/**
* ------------------------------------------------------------------------
* Constants
2017-09-20 14:19:10 +02:00
* ------------------------------------------------------------------------
*/
const closest = Polyfill.closest
const find = Polyfill.find
const findOne = Polyfill.findOne
2017-09-26 10:04:31 +02:00
2017-09-20 14:19:10 +02:00
return {
matches(element, selector) {
return element.matches(selector)
2017-09-20 14:19:10 +02:00
},
2017-08-26 12:44:26 +02:00
2017-09-26 10:04:31 +02:00
find(selector, element = document.documentElement) {
2017-09-20 14:19:10 +02:00
if (typeof selector !== 'string') {
return null
}
2017-08-26 12:44:26 +02:00
return find.call(element, selector)
2017-09-20 14:19:10 +02:00
},
2017-08-26 12:44:26 +02:00
2017-09-26 10:04:31 +02:00
findOne(selector, element = document.documentElement) {
2017-09-20 14:19:10 +02:00
if (typeof selector !== 'string') {
return null
}
return findOne.call(element, selector)
2017-09-26 10:04:31 +02:00
},
children(element, selector) {
if (typeof selector !== 'string') {
return null
2017-09-20 14:19:10 +02:00
}
2017-08-21 09:11:37 +02:00
2017-09-26 10:04:31 +02:00
const children = Util.makeArray(element.children)
return children.filter((child) => this.matches(child, selector))
2017-09-20 14:19:10 +02:00
},
2017-09-25 09:09:01 +02:00
parents(element, selector) {
if (typeof selector !== 'string') {
return null
}
const parents = []
let ancestor = element.parentNode
while (ancestor && ancestor.nodeType === Node.ELEMENT_NODE) {
if (ancestor.matches(selector)) {
2017-09-25 09:09:01 +02:00
parents.push(ancestor)
}
ancestor = ancestor.parentNode
}
return parents
},
2017-09-20 14:19:10 +02:00
closest(element, selector) {
return closest(element, selector)
2017-09-25 09:09:01 +02:00
},
prev(element, selector) {
if (typeof selector !== 'string') {
return null
}
const siblings = []
let previous = element.previousSibling
while (previous) {
if (previous.matches(selector)) {
2017-09-25 09:09:01 +02:00
siblings.push(previous)
}
previous = previous.previousSibling
}
return siblings
2017-09-20 14:19:10 +02:00
}
2017-08-21 09:11:37 +02:00
}
2017-09-20 14:19:10 +02:00
})()
2017-08-21 09:11:37 +02:00
export default SelectorEngine