Re: [whatwg/dom] Add an optional options dictionary to `closest` to allow jumping across shadow boundaries (Issue #1265)

GarrettS left a comment (whatwg/dom#1265)

Idea is, walk parentNode, and when you hit a ShadowRoot, step to its .host instead of stopping.

One arg native closest deliberately does _not_ cross shadow boundaries. It walks within the node's tree scope and stops at the shadow root — that is the encapsulation, enforced by refusing to climb through the host. That's what you wanna bust through.

This version uses a hypothetical getParentOrHost, so it stops where you tell it to stop.

The getComposedParent idea I put up earlier makes sense for thinking about it in terms of shadow root, in DOM lite, "ComposedParent" is the wrong name. An internal getParentOrHost() would make more sense:
```
while (currentNode) {
  if (currentNode.matches(selector)) return currentNode;
  if (currentNode === ancestor) break; // Stops it from going any further up
  currentNode = currentNode.getParentOrHost();
}
```
That'd make it possible to run closest(selectorText, ancestor) in either context: DOM light or a boundary-crossing shadow DOM, where an explicitly supplied node ancestor means it searches until it finds either the element matching the given selector or the ancestor node.

Looking up chromium source, I found:
```
  Element* Node::ParentOrShadowHostElement() const {
    ContainerNode* parent = ParentOrShadowHostNode();
    if (!parent) return nullptr;
    if (auto* shadow_root = DynamicTo<ShadowRoot>(parent))
      return &shadow_root->host();      // <- crosses the boundary
    return DynamicTo<Element>(parent);
  }
```
https://raw.githubusercontent.com/chromium/chromium/master/third_party/blink/renderer/core/dom/node.cc

So it's possible, and it looks like there's code for it.

-- 
Reply to this email directly or view it on GitHub:
https://github.com/whatwg/dom/issues/1265#issuecomment-4654230981
You are receiving this because you are subscribed to this thread.

Message ID: <whatwg/dom/issues/1265/4654230981@github.com>

Received on Monday, 8 June 2026 22:48:57 UTC