I spent some time searching but have only seen too many regular "walk the DOM" blogs or answers that only go one level UP with getRootnode()
Pseudo code:
HTML
<element-x>
//# shadow-root
<element-y>
<element-z>
//# shadow-root
let container = this.closest('element-x');
</element-z>
</element-y>
</element-x>
The standard element.closest()
function does not pierce shadow boundaries;
So this.closest('element-x')
returns null
because there is no <element-x>
within <element-z>
shadowDom
Goal:
<element-x>
子孫の内部から検索<element z>
(ネストされた任意のレベル)
必須:
.closest()
(シャドウ) DOMをたどって検索する (再帰的)関数<element-x>
注: 要素には ShadowDOM がある場合とない場合があります (参照<element y>
: lightDOM のみ)
明日は自分でできますし、そうするつもりです。明るい心がすでにそれを行っているのではないかと思っただけです。
資力:
- https://developer.mozilla.org/en-US/docs/Web/API/Node/getRootNode
- https://developer.mozilla.org/en-US/docs/Web/API/ShadowRoot/host
アップデート
これは、以下の回答からの UNminified コードです。
closestElement(selector, base = this) {
function __closestFrom(el) {
if (!el || el === document || el === window) return null;
let found = el.closest(selector);
if (found)
return found;
else
__closestFrom(el.getRootNode().host);
}
return __closestFrom(base);
}
アップデート #2
BaseElement のメソッドに変更しました。
closestElement(selector, el = this) {
return (
(el && el != document && el != window && el.closest(selector)) ||
this.closestElement(selector, el.getRootNode().host)
);
}