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

68 lines
1.6 KiB
JavaScript
Raw Normal View History

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)
* --------------------------------------------------------------------------
*/
// 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)
let fnClosest = null
if (!Element.prototype.closest) {
fnClosest = (element, selector) => {
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
}
} else {
// eslint-disable-next-line arrow-body-style
fnClosest = (element, selector) => {
return element.closest(selector)
}
}
2017-08-21 09:11:37 +02:00
const SelectorEngine = {
matches(element, selector) {
return fnMatches.call(element, selector)
},
2017-08-21 09:11:37 +02:00
find(element = document, selector) {
2017-08-21 09:11:37 +02:00
if (typeof selector !== 'string') {
return null
}
let selectorType = 'querySelectorAll'
if (selector.indexOf('#') === 0) {
selectorType = 'getElementById'
selector = selector.substr(1, selector.length)
}
return element[selectorType](selector)
2017-08-21 09:11:37 +02:00
},
closest(element, selector) {
return fnClosest(element, selector)
2017-08-21 09:11:37 +02:00
}
}
export default SelectorEngine