日本語

How to Fix Playwright’s “Element is not attached to the DOM”

​​Playwright​E2E Testing,Troubleshooting,TypeScript

In Playwright E2E tests, elementHandle.click: Element is not attached to the DOM appears because the test operated on an old element that is no longer attached to the DOM. An element obtained with page.$() or similar becomes detached once the page re-renders and replaces it with a new element. This happens in tests for screens that redraw a list each time a button is pressed, or that reload data and redraw the list. Rewriting the test to operate through a locator such as page.getByRole() removes the error.

In my test environment, I reproduced this error in two scenarios and included the messages exactly as they were printed. I also confirmed that the tests pass after the fix.

Note

The test environment was Ubuntu 24.04, Node.js 22.23.5, @playwright/test 1.63.0 (Chromium 158.0.8127.36, headless), and TypeScript 5.9.3. The test pages were served by a small server built with Node.js's http module, listening on port 3000. I did not test Firefox or WebKit, Windows or macOS, or pages built with frameworks such as React.

The test that fails

The page under test shows cat names, each with a "like" button. Pressing a button increments the count by one and redraws the entire list with innerHTML. Each redraw also replaces the buttons with new elements. The following code is the list part of the page's HTML.

html
<ul id="list"></ul>
<script>
  const cats = [{ name: 'たま', likes: 0 }, { name: 'みけ', likes: 0 }];
  function render() {
    // Rebuild the entire list (the buttons also become new elements).
    document.getElementById('list').innerHTML = cats.map((c, i) =>
      `<li>${c.name}:<span data-testid="likes-${i}">${c.likes}</span>
         <button data-index="${i}" aria-label="${c.name}にいいね">いいね</button></li>`).join('');
  }
  document.getElementById('list').addEventListener('click', (e) => {
    const i = e.target.dataset.index;
    if (i === undefined) return;
    cats[i].likes++;
    render();
  });
  render();
</script>

The test (tests/like.spec.ts) gets the Tama button once with page.$(), clicks it twice, and checks that the count becomes 2. The use section of the config file sets baseURL: 'http://localhost:3000'.

ts
import { test, expect } from '@playwright/test';

test('たまに2回いいねすると2になる', async ({ page }) => {
  await page.goto('/');
  const button = await page.$('button[aria-label="たまにいいね"]');
  await button!.click();
  await button!.click();
  await expect(page.getByTestId('likes-0')).toHaveText('2');
});

When I ran it, the test failed on the second click. The output is shown unchanged, except that the working directory path is replaced with /path/to/app.

text
$ npx playwright test

Running 1 test using 1 worker

  ✘  1 tests/like.spec.ts:3:5 › たまに2回いいねすると2になる (162ms)


  1) tests/like.spec.ts:3:5 › たまに2回いいねすると2になる ──────────────────────────────────────────────────────

    Error: elementHandle.click: Element is not attached to the DOM
    Call log:
      - attempting click action
        - waiting for element to be visible, enabled and stable


       5 |   const button = await page.$('button[aria-label="たまにいいね"]');
       6 |   await button!.click();
    >  7 |   await button!.click();
         |                 ^
       8 |   await expect(page.getByTestId('likes-0')).toHaveText('2');
       9 | });
      10 |
        at /path/to/app/tests/like.spec.ts:7:17

    Error Context: test-results/like-たまに2回いいねすると2になる/error-context.md

  1 failed
    tests/like.spec.ts:3:5 › たまに2回いいねすると2になる ───────────────────────────────────────────────────────

The first click succeeded. It redrew the list, which detached the button element that the variable was pointing to. The second click tried to press that detached button and failed.

An element from page.$() keeps pointing at the replaced old element

page.$() returns an ElementHandle, which points to one specific element on the page. The ElementHandle API reference notes that an ElementHandle keeps pointing at the same DOM element even when the element's text changes or when React reuses that element to render a different component, which can lead to unexpected behavior. The same page also says that ElementHandles are discouraged and recommends using locators and auto-waiting assertions (expect(locator)).

In my check, after one click I inspected the button variable. isConnected (whether it is attached to the DOM) was false, while textContent still read いいね. The element itself still existed, but it had been detached from the DOM.

text
isConnected: false
textContent: いいね

An element obtained through a locator's elementHandle() is also an ElementHandle, and it has the same problem. Clicking twice on an element from page.getByRole('button', { name: 'たまにいいね' }).elementHandle() failed with the same elementHandle.click: Element is not attached to the DOM.

Diagram comparing an element from page.$() with a locator. After the list is redrawn, the button from page.$() still points to the old button that has been detached from the DOM, so the second click fails with Element is not attached to the DOM. A locator searches the current DOM on each action, so it presses the new button and the second click also succeeds. (The labels in the image are in Japanese.)
After the list is redrawn, an ElementHandle points to the old button, while a locator points to the new one

Fix: operate through a locator

The fix is to avoid ElementHandles and operate through a locator. Don't pull the element out with await; store the return value of page.getByRole() directly in the variable.

ts
import { test, expect } from '@playwright/test';

test('たまに2回いいねすると2になる', async ({ page }) => {
  await page.goto('/');
  const button = page.getByRole('button', { name: 'たまにいいね' });
  await button.click();
  await button.click();
  await expect(page.getByTestId('likes-0')).toHaveText('2');
});

When I ran it, the test passed and the error was gone.

text
$ npx playwright test

Running 1 test using 1 worker

  ✓  1 tests/like.spec.ts:3:5 › たまに2回いいねすると2になる (206ms)

  1 passed (833ms)

As the ElementHandle API reference describes, a locator does not hold the element itself; it holds the way to find the element. According to the locator documentation, each time you act through a locator, it looks up the current DOM element on the page. So even though the first click redraws the list, the second click finds and presses the new button. The elementHandle.click() documentation also recommends using locator.click() instead.

When the list is redrawn after reloading data

The same error occurs when the page redraws the list later, even if no button was pressed. In my test, when the page was opened with ?refetch in the URL, it redrew the list after 300 milliseconds, as if the data had been reloaded, and then displayed the text "Load complete". I added <p id="status"></p> before <ul id="list"></ul> in the HTML shown earlier, and appended the following code after the final render(); in the <script>.

js
// For ?refetch, after 300 ms, pretend the data has been reloaded and rebuild the list.
if (location.search === '?refetch') {
  setTimeout(() => {
    render();
    document.getElementById('status').textContent = '読み込み完了';
  }, 300);
}

The test opens the page, gets the button with page.$() right away, waits for "Load complete" to appear, and then clicks.

ts
test('読み込み直したあとにいいねすると1になる', async ({ page }) => {
  await page.goto('/?refetch');
  const button = await page.$('button[aria-label="たまにいいね"]');
  await expect(page.getByText('読み込み完了')).toBeVisible();
  await button!.click();
  await expect(page.getByTestId('likes-0')).toHaveText('1');
});

This test also failed on the click line with elementHandle.click: Element is not attached to the DOM. The button was obtained before the redraw, so button points to the old button. When I changed button to page.getByRole('button', { name: 'たまにいいね' }), the test passed.

When you see this error, trace back to where the variable used on the failing line was created. If an element was obtained with await through something like await page.$() or await locator.elementHandle(), replace that line with a locator.

​Posted by 86