Skip to content

Commit f674dba

Browse files
committed
feat(dom): clulib.dom.matches + clulib.dom.closest
1 parent 10441e1 commit f674dba

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

lib/dom/dom.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
goog.provide('clulib.dom');
2+
3+
goog.require('goog.dom');
4+
5+
/**
6+
* Returns true if the [element] would be selected by the specified
7+
* [selector] string, false otherwise.
8+
*
9+
* @param {Element} element
10+
* @param {string} selector
11+
* @returns {boolean}
12+
*/
13+
clulib.dom.matches = function (element, selector) {
14+
/**
15+
* @type {function(this:Element, string):boolean}
16+
*/
17+
let matches = element['matches'] ||
18+
element['matchesSelector'] ||
19+
element['webkitMatchesSelector'] ||
20+
element['mozMatchesSelector'] ||
21+
element['msMatchesSelector'];
22+
23+
return matches.call(element, selector);
24+
};
25+
26+
/**
27+
* Returns the closest ancestor of the specified [element] (or the specified element itself)
28+
* which matches the [selector]. Returns null, if there is no such ancestor.
29+
*
30+
* @param {Element} element
31+
* @param {string} selector
32+
* @returns {?Element}
33+
*/
34+
clulib.dom.closest = function (element, selector) {
35+
if (element['closest'] != null) {
36+
return /** @type {?Element} */ (element['closest'](selector));
37+
} else {
38+
return /** @type {?Element} */ (goog.dom.getAncestor(element, node => {
39+
if (goog.dom.isElement(node))
40+
return clulib.dom.matches(/** @type {Element} */ (node), selector);
41+
else
42+
return false;
43+
}, true));
44+
}
45+
};

0 commit comments

Comments
 (0)