diff --git a/packages/playwright-core/src/server/injected/injectedScript.ts b/packages/playwright-core/src/server/injected/injectedScript.ts index c3d6e296e5d14..4042ab5b497b4 100644 --- a/packages/playwright-core/src/server/injected/injectedScript.ts +++ b/packages/playwright-core/src/server/injected/injectedScript.ts @@ -531,10 +531,10 @@ export class InjectedScript { if (!element.matches('a, input, textarea, button, select, [role=link], [role=button], [role=checkbox], [role=radio]') && !(element as any).isContentEditable) { // Go up to the label that might be connected to the input/textarea. - element = element.closest('label') || element; + const enclosingLabel: HTMLLabelElement | null = element.closest('label'); + if (enclosingLabel && enclosingLabel.control) + element = enclosingLabel.control; } - if (element.nodeName === 'LABEL') - element = (element as HTMLLabelElement).control || element; } return element; } diff --git a/tests/page/retarget.spec.ts b/tests/page/retarget.spec.ts index 94e0f440e7c5e..6c09d3b90771a 100644 --- a/tests/page/retarget.spec.ts +++ b/tests/page/retarget.spec.ts @@ -109,6 +109,7 @@ it('enabled/disabled retargeting', async ({ page, asset }) => { { dom: domInButton(``), enabled: true, locator: 'input' }, { dom: domInLink(``), enabled: true, locator: 'input' }, { dom: domInButton(``, { disabled: true }), enabled: true, locator: 'input' }, + { dom: domInLabel(`
`), enabled: true, locator: 'li' }, { dom: domInLabel(``), enabled: false, locator: 'label' }, { dom: domLabelFor(``), enabled: false, locator: 'label' }, @@ -116,6 +117,7 @@ it('enabled/disabled retargeting', async ({ page, asset }) => { { dom: domInButton(``), enabled: false, locator: 'input' }, { dom: domInLink(``), enabled: false, locator: 'input' }, { dom: domInButton(``, { disabled: true }), enabled: false, locator: 'input' }, + { dom: domInLabel(``), enabled: false, locator: 'li' }, ]; for (const { dom, enabled, locator } of cases) { await it.step(`"${locator}" in "${dom}" should be enabled=${enabled}`, async () => {