microsoft/playwright · error · Error

Target element must belong to the root's subtree

Error message

Target element must belong to the root's subtree

What it means

Error "Target element must belong to the root's subtree" thrown in microsoft/playwright.

Source

Thrown at packages/injected/src/selectorGenerator.ts:123

    }
    const selector = joinTokens(targetTokens);
    const parsedSelector = injectedScript.parseSelector(selector);
    return {
      selector,
      elements: injectedScript.querySelectorAll(parsedSelector, options.root ?? targetElement.ownerDocument)
    };
  } finally {
    endDOMCaches();
    endAriaCaches();
    injectedScript._evaluator.end();
  }
}

type InternalOptions = GenerateSelectorOptions & { isRecursive?: boolean };

function generateSelectorFor(cache: Cache, injectedScript: InjectedScript, targetElement: Element, options: InternalOptions): SelectorToken[] | null {
  if (options.root && !isInsideScope(options.root, targetElement))
    throw new Error(`Target element must belong to the root's subtree`);

  if (targetElement === options.root)
    return [{ engine: 'css', selector: ':scope', score: 1 }];
  if (targetElement.ownerDocument.documentElement === targetElement)
    return [{ engine: 'css', selector: 'html', score: 1 }];

  let result: SelectorToken[] | null = null;
  const updateResult = (candidate: SelectorToken[]) => {
    if (!result || combineScores(candidate) < combineScores(result))
      result = candidate;
  };

  const candidates: { candidate: SelectorToken[], isTextCandidate: boolean }[] = [];
  for (const candidate of buildTextCandidates(injectedScript, targetElement, !options.isRecursive, options))
    candidates.push({ candidate, isTextCandidate: true });
  for (const token of buildNoTextCandidates(injectedScript, targetElement, options)) {
    if (options.omitInternalEngines && token.engine.startsWith('internal:'))
      continue;

View on GitHub (pinned to c8fc3bf8d3)

When it happens

Trigger: Thrown at packages/injected/src/selectorGenerator.ts:123 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of microsoft/playwright@c8fc3bf8d3 (2026-08-12). Data as JSON: /api/errors/3f6f16f6fee05bd9. Report an issue: GitHub.