Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Fix the driver behind crashes, sound loss and screen glitches3Repair Windows errors before they cause bigger problemsSome links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.
Use a Playwright locator’s evaluate() method, call the DOM element’s setAttribute(name, value) in the page context, and verify the result with expect(locator).toHaveAttribute(). This changes the element currently matched by the locator; it does not automatically update framework-managed application state.
The direct Playwright pattern
locator.evaluate() runs a callback in the browser page and passes the matched DOM element as the callback’s first argument. Inside that callback, call the standard DOM method setAttribute():
await locator.evaluate((element) => {
element.setAttribute('data-state', 'ready');
});
A complete Playwright Test example looks like this:
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');
});
The callback executes in the page, not in your Node.js test process. The first parameter is the element matched by the locator, so the mutation uses normal browser DOM APIs.
#1 Best Overall
- CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
- INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
- THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
- WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
- A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents
Choose a locator that expresses the intended element
Playwright locators re-resolve the current matching element when used. That behavior helps when a page re-renders between steps. Prefer a locator based on user-facing meaning or an explicit testing contract rather than a selector that depends on incidental markup.
| Locator | Example | When it fits | Trade-off |
|---|---|---|---|
| Role and accessible name | page.getByRole('button', { name: 'Save' }) |
The element has a reliable semantic role and accessible name. | Expresses what a user recognizes; the accessible name must remain accurate. |
| Test ID | page.getByTestId('save') |
The application exposes a stable test contract. | Stable for tests, but requires the test ID to be maintained in the product. |
| CSS | page.locator('[data-state="idle"]') |
You need an attribute or CSS relationship not covered by a higher-level locator. | Can become brittle when implementation details change. |
| XPath | page.locator('xpath=//button[@type="submit"]') |
A structural query is genuinely required. | Often tied closely to document structure, so refactors can break it. |
The default test ID attribute is data-testid. Playwright can be configured to use a different test ID attribute when a project has another explicit convention.
Pass a dynamic attribute value
The optional second argument to evaluate() is passed to the page callback as its second parameter. Keep data outside the callback when the value comes from a test variable, fixture, or generated input:
Free tools Windows power users keep installed
One-click scans. No signup required.
import { test, expect } from '@playwright/test';
test('sets a value supplied by the test', async ({ page }) => {
const state = 'ready';
const saveButton = page.getByTestId('save');
await saveButton.evaluate(
(element, value) => element.setAttribute('data-state', value),
state,
);
await expect(saveButton).toHaveAttribute('data-state', state);
});
This form makes the boundary clear: element is the page-side DOM node and value is the argument supplied by the test. Keep the value serializable so Playwright can transfer it to the browser context.
Verify the attribute with a web-first assertion
After the mutation, use Playwright Test’s locator assertion:
Rank #2
- CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
- 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
- SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
- INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
- THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
await expect(saveButton).toHaveAttribute('data-state', 'ready');
toHaveAttribute() checks that the locator resolves to an element with the expected attribute and value. It is preferable to an immediate one-time read when the page may be settling, because locator assertions provide Playwright’s retrying, web-first behavior.
Read an attribute without asserting it
When the purpose is inspection rather than a test failure, call getAttribute():
Recommended Free Tools
const state = await saveButton.getAttribute('data-state');
console.log(state);
getAttribute() retrieves the current value; it does not set one. For a test contract, retain toHaveAttribute() so an unexpected value produces an assertion failure with Playwright’s normal diagnostics.
Mutation versus a normal Playwright action
evaluate() is appropriate when the requirement is an arbitrary DOM mutation, such as adding a custom data-* attribute for a browser-side condition. It is not a substitute for an interaction that Playwright already models.
- For an input’s value, use the corresponding locator action, such as
locator.fill(), instead of setting an unrelated attribute. - For a button click, use
locator.click()so the test follows the user interaction path. - Use
evaluate()when the test specifically needs to call a DOM API that has no more direct Playwright action.
Choosing an action that matches the user-visible operation generally keeps the test’s intent and application behavior aligned.
Rank #3
- Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
- Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
- Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
- In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
- Ultra-thin bezels: Maximize your viewing experience with thin bezels.
What this changes—and what it does not
The page DOM changes immediately
setAttribute() changes the matched element in the current document. The subsequent assertion observes that DOM value through the locator.
Framework state may be different
A direct DOM mutation is not established as a way to update state held by a front-end framework. A framework may overwrite the attribute during its next render, or its internal state may remain unchanged. If the attribute represents framework-managed state, use the application’s supported interaction or state pathway and assert the externally observable result instead of relying on a DOM-only write.
Re-rendering can replace the node
Because locators resolve the current match, a later action can target a newly rendered element. If the application re-renders after your mutation, assert the state at the point where it matters and investigate whether the supported application pathway is required.
Common failures and fixes
“Locator resolved to multiple elements”
Cause: the selector is not unique. Fix: refine the role and accessible name, use an explicit test ID, or add a narrowly scoped locator. Avoid selecting an arbitrary first match unless that is the contract you intend to test.
“Locator resolved to no elements” or a timeout
Cause: the element is not present, the locator is incorrect, or the page has not reached the state in which it is rendered. Fix: check the role/name or test ID in the rendered page, wait for the application state that creates the element, and prefer a locator that describes the element’s stable contract.
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Rank #4
- CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
- SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
- MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
- KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
- INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient
The assertion sees the old value
Cause: application code re-rendered the element or replaced the attribute after the mutation. Fix: determine whether the attribute is framework-managed; if it is, perform the supported user or application action and assert the resulting state. If it is a purely test-side DOM mutation, place the assertion immediately after the evaluate call and inspect for page scripts that rewrite it.
The callback throws a browser-side error
Cause: the callback assumes a property or value that is invalid for the matched element. Fix: keep the callback focused on the DOM operation, confirm that the locator points to the intended element type, and pass a defined, serializable value.
The attribute is present but the value is unexpected
Cause: an earlier test, application code, or a different matched element supplied the value. Fix: use an isolated page state, make the locator unique, and assert the exact value with toHaveAttribute() rather than checking only that the attribute exists.
Reliability and maintenance guidance
- Keep the locator and the mutation close together so the element-selection contract is easy to review.
- Use a descriptive attribute name, such as
data-state, when the attribute is intended for test or page logic. - Prefer role/name locators for user-facing controls and test IDs for an explicit testing contract; reserve structural CSS or XPath for cases that need them.
- Assert the exact attribute value that matters. A presence-only check can pass while the application is in the wrong state.
- Re-check the API against the Playwright version installed by your project. The official documentation referenced for this technique was checked on September 29, 2026, and versioned APIs can change.
There is no published performance figure associated with this operation in the cited Playwright documentation. In practice, the main reliability variables are locator uniqueness, page re-rendering, and whether the attribute is controlled by application state.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Or skip the browser setup
If your actual goal is to obtain an image or PDF of a web page rather than mutate its DOM in a test, ScreenshotNeo provides a single-request website screenshot API. It is separate from Playwright and does not replace a DOM assertion, but it can remove the need to maintain browser-launch code for capture workflows.
Best Value
- 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
- 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
- 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.
ScreenshotNeo accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and whether the request was billed. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf tools to Claude, Cursor, and other MCP clients. Every plan includes the feature set, including full-page capture, element selection by CSS selector, device and viewport controls, custom CSS and JavaScript, waits, request blocking, cookies and headers, PDF options, caching, signed links, asynchronous jobs, bulk capture, a usage API, and an OpenAPI specification.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
See the ScreenshotNeo API documentation for request options. The same service can be called from Python:
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
Or from Node.js:
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
The Free plan includes 1,000 screenshots per month with no card required. Paid plans start at $5 for 3,000 screenshots; yearly billing gives two months free. Create a free ScreenshotNeo account to try the capture API without adding a card.
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Repair Windows errors before they cause bigger problemsFix Now →FAQ
Can I set an HTML attribute with a locator action instead of evaluate()?
For an arbitrary attribute name and value, the documented approach is to run element.setAttribute() inside locator.evaluate(). Use a dedicated Playwright action when the operation is a normal user interaction, such as filling a field.
Why does the value disappear after the test sets it?
A page render may replace the element or rewrite its attributes. That indicates the DOM mutation is not the application’s state pathway; trigger the supported application behavior when persistence across renders is required.
Which method should I use to check the value?
Use toHaveAttribute() for an assertion that should fail when the contract is wrong. Use getAttribute() when you only need to read the current value for test logic or diagnostics.
Can the value be generated at runtime?
Yes. Supply it as the second argument to evaluate(). This keeps dynamic data separate from the page callback while still passing it to the matched element’s DOM operation.
Frequently Asked Questions
Does setAttribute trigger my framework’s state update?
Not necessarily. A direct page-context DOM mutation is distinct from a framework’s state-management pathway; use the supported application interaction when framework state must change.
What should I do if the locator matches a re-rendered element?
Keep using a locator rather than a cached element handle, and assert the attribute at the point where the result is required. If the render overwrites it, test through the application’s supported pathway.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

