Add a util to support querySelector with shadow DOM compatible.

This util meant to work as a polyfill for `$$` in polymer as `$$`
won't work in shadow DOM. But this util will only work when
selector is within one shadow host, won't work when selector
is crosing multiple shadow hosts.

Change-Id: Ie9e36dc3fb9c18c89aa1580ccf15523a7fa49c85
This commit is contained in:
Tao Zhou
2019-09-17 17:12:43 +02:00
parent 2cf768e8ac
commit d382b5f666

View File

@@ -95,5 +95,38 @@
return style;
};
/**
* Query selector on a dom element.
*
* This is shadow DOM compatible, but only works when selector is within
* one shadow host, won't work if your selector is crossing
* multiple shadow hosts.
*
*/
util.querySelector = (el, selector) => {
let nodes = [el];
let element = null;
while (nodes.length) {
const node = nodes.pop();
// Skip if it's an invalid node.
if (!node || !node.querySelector) continue;
// Try find it with native querySelector directly
element = node.querySelector(selector);
if (element) {
break;
} else if (node.shadowRoot) {
// If shadowHost detected, add the host and its children
nodes = nodes.concat(Array.from(node.children));
nodes.push(node.shadowRoot);
} else {
nodes = nodes.concat(Array.from(node.children));
}
}
return element;
};
window.util = util;
})(window);