Add helper method to query select all dom elements
This helper method was introduced by Tao in stable-3.2 as part of another change [1]. It would also help in 3.1, where the shadow dom is also already used. [1] https://gerrit-review.googlesource.com/c/gerrit/+/250189 Inspired-by: Tao Zhou <taoalpha@google.com> Change-Id: I04dd9d98bf740eaf8558b24a60b9e535e225eb17
This commit is contained in:
parent
7f38d1c685
commit
16c095e26c
@ -128,5 +128,41 @@
|
||||
return element;
|
||||
};
|
||||
|
||||
/**
|
||||
* Query selector all dom elements matching with certain selector.
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* Note: this can be very expensive, only use when have to.
|
||||
*/
|
||||
util.querySelectorAll = (el, selector) => {
|
||||
let nodes = [el];
|
||||
const results = new Set();
|
||||
while (nodes.length) {
|
||||
const node = nodes.pop();
|
||||
|
||||
if (!node || !node.querySelectorAll) continue;
|
||||
|
||||
// Try find all from regular children
|
||||
[...node.querySelectorAll(selector)]
|
||||
.forEach(el => results.add(el));
|
||||
|
||||
// Add all nodes with shadowRoot and loop through
|
||||
const allShadowNodes = [...node.querySelectorAll('*')]
|
||||
.filter(child => !!child.shadowRoot)
|
||||
.map(child => child.shadowRoot);
|
||||
nodes = nodes.concat(allShadowNodes);
|
||||
|
||||
// Add shadowRoot of current node if has one
|
||||
// as its not included in node.querySelectorAll('*')
|
||||
if (node.shadowRoot) {
|
||||
nodes.push(node.shadowRoot);
|
||||
}
|
||||
}
|
||||
return [...results];
|
||||
};
|
||||
|
||||
window.util = util;
|
||||
})(window);
|
||||
|
Loading…
Reference in New Issue
Block a user