How to Set an Attribute Value on a DOM Element with Playwright
Use a Playwright locator’s evaluate() method to call setAttribute() in the page, then verify the result with toHaveAttribute().

To set an attribute on a DOM element with Playwright, locate the element and call its native setAttribute() method inside locator.evaluate(). Then verify the value with Playwright Test’s retrying expect(locator).toHaveAttribute() assertion.
import { test, expect } from '@playwright/test';
test('sets a DOM attribute', async ({ page }) => {
const saveButton = page.getByRole('button', { name: 'Save' });
await saveButton.evaluate((element) => {
element.setAttribute('data-state', 'ready');
});
await expect(saveButton).toHaveAttribute('data-state', 'ready');
});
locator.evaluate() runs its callback in the page context and passes the matched element to it. The optional second argument lets you pass a dynamic value without embedding it in the callback. See the official Locator API and Playwright’s locator guidance.
1. Decide whether direct attribute mutation is the right operation
setAttribute(name, value) changes an attribute on the DOM element currently matched by the locator. This is useful when the test specifically needs to exercise an attribute mutation, such as setting a test fixture marker or preparing a page state that cannot be reached through the product’s normal interface.
It does not simulate a user action. If the user would type into an input, use Playwright’s fill(); if they would click a control, use click(). If the attribute represents application state managed by a framework, a direct DOM change may not update that framework’s state and could be replaced on a later render. Use the application’s supported interaction or state pathway when that behavior is what the test needs to cover.
2. Install and run the example
The following small project runs the test against a local page. Install Playwright Test, create a page containing a Save button, and run the test. The fixture page makes the example self-contained: the test changes the button’s data-state attribute and asserts the result.

npm init -y
npm install --save-dev @playwright/test
npx playwright install chromium
Create attribute.spec.ts:
import { test, expect } from '@playwright/test';
test('sets and verifies an attribute', async ({ page }) => {
await page.setContent('<button>Save</button>');
const button = page.getByRole('button', { name: 'Save' });
await button.evaluate((element) => {
element.setAttribute('data-state', 'ready');
});
await expect(button).toHaveAttribute('data-state', 'ready');
});
Run it with npx playwright test attribute.spec.ts. For an existing application test, remove page.setContent() and use the page’s normal navigation or fixture setup. Playwright’s role locator is appropriate when the role and accessible name uniquely identify the control; a test ID is another clear contract when the application exposes one.
3. Choose a locator that identifies the intended element
Locators are Playwright’s main way to find elements. They re-resolve the matching element when used, which helps when a page re-renders. Prefer selectors that express the test’s intent and remain meaningful if the DOM layout changes.
| Locator | Good fit | Example |
|---|---|---|
| Role and accessible name | A user-facing control with a reliable name | page.getByRole('button', { name: 'Save' }) |
| Label | A form field associated with visible label text | page.getByLabel('Email address') |
| Test ID | An explicit test contract in the application | page.getByTestId('save') |
| CSS or XPath | A structural or attribute target without a suitable semantic locator | page.locator('[data-state="idle"]') |
CSS and XPath are available, but selectors tied to DOM structure can break when markup changes. Use them when the structure or attribute itself is the behavior under test, rather than as a default for every element. Playwright uses data-testid by default for test IDs; the configured test ID attribute can be changed in Playwright configuration.
If a locator could match multiple elements, narrow it before mutating. For example, scope it to a dialog or a specific row. Avoid selecting the first match just to silence ambiguity unless the order is part of the test contract: otherwise the test may alter the wrong element while appearing to succeed.
4. Pass a dynamic attribute value
Use the second argument to evaluate() to pass a runtime value into the page callback. This keeps data separate from executable code and avoids constructing a callback string.
const saveButton = page.getByTestId('save');
const state = 'ready';
await saveButton.evaluate(
(element, value) => element.setAttribute('data-state', value),
state,
);
await expect(saveButton).toHaveAttribute('data-state', state);
The callback’s first parameter is the matched element; its second parameter receives the value supplied to evaluate(). The value must be serializable for transfer to the page context. Use a string for attribute values. The DOM’s setAttribute() method treats the value as a string, so if you pass a number or boolean, convert it explicitly if you want the intended textual representation.
For several independent values, pass a serializable object:
await saveButton.evaluate(
(element, attrs) => {
element.setAttribute('data-state', attrs.state);
element.setAttribute('data-owner', attrs.owner);
},
{ state: 'ready', owner: 'checkout' },
);
Keep multi-attribute mutations limited to what the test is arranging. If the application is expected to set these attributes as a consequence of a user action, drive that action and assert the resulting state instead of making the test pass by setting the expected output itself.
5. Verify the mutation with a web-first assertion
Use await expect(locator).toHaveAttribute(name, value) when the test expects a value. Playwright retries web-first assertions until they pass or the assertion timeout expires, helping account for asynchronous page changes. The assertions guide documents toHaveAttribute().
await expect(saveButton).toHaveAttribute('data-state', 'ready');
When the attribute’s presence matters but its exact value does not, use the supported assertion form for presence in your installed Playwright version, or read the attribute and make an explicit assertion. For regular-expression checks, use a regular expression as the expected value:
await expect(saveButton).toHaveAttribute('aria-label', /save/i);
To read rather than assert, use getAttribute():
const value = await saveButton.getAttribute('data-state');
expect(value).toBe('ready');
getAttribute() reads the current value; it does not set it. For an assertion that should wait for a value to become correct, prefer toHaveAttribute() over a one-time read. A one-time read can race with an update that has not happened yet.
6. Understand the DOM and application-state edge cases
- Missing attribute:
setAttribute()creates the attribute if it does not exist. An empty string is still a present attribute with an empty value. - Existing attribute: calling
setAttribute()with the same name replaces its previous value. - Boolean HTML attributes: HTML boolean attributes are generally controlled by presence. Setting one to the string
"false"still leaves it present. To remove an attribute, callremoveAttribute(); do not assume a string value of false disables it. - Attribute name and case: HTML attribute names are generally normalized by the DOM, while XML documents can have different case behavior. Use the exact spelling expected by the document and assertion.
- Re-rendering: a framework may render the element again and overwrite a direct mutation. If the value disappears, establish it through the app’s normal mechanism or assert before a re-render.
- Events:
setAttribute()does not automatically perform a user gesture or guarantee that application event handlers run. Dispatching events manually is a separate choice and does not necessarily reproduce browser input behavior. - Detached element: if the page removes or replaces the element during evaluation, the operation may fail or affect an element that is no longer displayed. Reacquire through the locator and assert the visible outcome.
These distinctions matter most for attributes that reflect live control state. For example, an input’s current value is commonly represented by its DOM property; changing a related HTML attribute may not be equivalent to filling the field. Use the Playwright action that corresponds to the behavior under test.
7. Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Strict mode violation or multiple matches | The locator identifies more than one element. | Use a role, name, label, test ID, or scoped locator that identifies the intended element uniquely. Check the page for duplicate controls. |
| Timeout waiting for the locator | The element is not present yet, the page did not navigate, or the locator is incorrect. | Confirm navigation and page state; inspect the locator with Playwright’s trace or locator debugging tools; use a stable selector. |
| Attribute assertion fails immediately after mutation | The wrong locator was asserted, the callback changed another node, or application code re-rendered the element. | Use the same locator for the mutation and assertion, confirm it is unique, and determine whether app state should own the change. |
| Expected value differs by capitalization or formatting | Attribute values are strings and comparisons are exact unless a regex is used. | Assert the exact serialized value, normalize deliberately, or use a regular expression when only a pattern matters. |
| The page looks unchanged | The changed attribute has no visual effect, or it is not the attribute that drives the UI. | Assert the attribute itself for a DOM-focused test. For user-visible behavior, use the supported application action and assert its visible result. |
| Works once, then fails after navigation or rerender | Direct mutation is ephemeral and may be lost when the DOM is reconstructed. | Set up the state through the app’s supported route, fixture, or interaction, then assert the behavior that should persist. |
For difficult failures, capture a Playwright trace and inspect the locator, DOM snapshot, and timing around the mutation. This is especially useful when the page asynchronously replaces controls or when the locator’s match changes between setup and assertion.
8. Performance, reliability, and cost
A single evaluate() call is a page-context operation, so keep it focused: mutate only the target element and pass simple serializable arguments. Avoid repeatedly querying the DOM inside large loops when one locator operation can make the intended change. The bigger reliability cost is usually selector brittleness or fighting framework state, not the attribute assignment itself.

Use web-first assertions for conditions that may appear asynchronously; avoid adding arbitrary sleeps as a substitute for synchronization. If you are setting an attribute purely to prepare a test, make that setup obvious in the test name and keep the later assertion about the actual behavior distinct. That prevents a test from merely verifying its own setup.
Playwright is open source; this code path does not require a ScreenshotNeo account or API charge. If the task changes from manipulating a page in a browser test to producing screenshots of remote websites, ScreenshotNeo is a separate website screenshot API and MCP server. Its pricing and included features are listed at ScreenshotNeo.
Or skip the browser setup
For a screenshot of a website, use ScreenshotNeo’s one-call API instead of launching and maintaining a browser. This does not set DOM attributes; it returns a screenshot or PDF. See the ScreenshotNeo API documentation.
curl -G "https://api.screenshotneo.com/v1/shot" \
-d access_key=YOUR_API_KEY \
--data-urlencode url=https://stripe.com \
-o shot.webp
Cookie banners, newsletter popups, and chat widgets are removed before the shot, and each cleanup step can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits cost nothing; response headers report the page verdict and billing status. Its MCP server gives AI agents tools to take screenshots, get page information, and capture PDFs. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. Sign up for 1,000 free screenshots a month, with no card required.
FAQ
Can I use locator.evaluate() to call setAttribute()?
Yes. The callback receives the matched DOM element in the page context, so it can call element.setAttribute(name, value).
Can I use getAttribute() to set an attribute?
No. getAttribute(name) reads a value. Use setAttribute(name, value) inside evaluate() to change one.
Will the change survive a page reload?
No persistence is implied by a DOM mutation. A reload recreates the page, and an application re-render can replace the element. Store state through the application if it needs to persist.
Should I set an attribute to false to turn it off?
For HTML boolean attributes, absence usually represents false. Remove the attribute when that is the intended state; the string "false" is still present.
Does this trigger the same behavior as a user interaction?
No. It mutates the DOM directly. Use Playwright’s user-facing actions when the test should cover what a user does.


