Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use a Playwright locator’s evaluate() method to run element.setAttribute(name, value) in the page context, then verify the result with Playwright’s web-first expect(locator).toHaveAttribute() assertion. This changes the DOM attribute on the currently matched element.

Set an attribute with locator.evaluate()

The following TypeScript test finds a Save button by its accessible role and name, sets a data-state attribute, and checks the resulting value.

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');
});

evaluate() executes its callback in the browser page, not in Node.js. The matched DOM element is passed as the callback’s first argument, so standard DOM APIs such as setAttribute() are available.

Pass a dynamic attribute value

Keep data outside the page callback by supplying evaluate()’s optional argument. Playwright passes that value to the callback as its second parameter.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Philips 24 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 241V8LB
  • 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
const state = 'ready';

await page.getByTestId('save').evaluate(
  (element, value) => element.setAttribute('data-state', value),
  state,
);

await expect(page.getByTestId('save')).toHaveAttribute('data-state', state);

This pattern is useful for values calculated by the test, fixture data, or a parameterized test case. Pass serializable values supported by Playwright’s evaluation mechanism; for a simple attribute, a string is the clearest choice.

Choose a locator that survives page changes

Locators are Playwright’s central mechanism for auto-waiting and retrying. A locator is resolved when it is used, which helps when a page re-renders between locating an element and evaluating it. Prefer a selector that expresses the element’s meaning or an explicit test contract.

Role and accessible name

const saveButton = page.getByRole('button', { name: 'Save' });

A role locator reflects what a user can perceive and interact with. Make the accessible name specific enough to identify the intended control.

Test ID

const saveButton = page.getByTestId('save');

By default, getByTestId() looks for data-testid. Playwright can be configured to use a different test-ID attribute when your application has an established convention. A test ID is an explicit contract between the page and the test, but it requires the application to expose that contract.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

CSS and XPath

const saveButton = page.locator('button.save');
const item = page.locator('//button[@data-action="save"]');

CSS and XPath are available when semantic locators or test IDs cannot express the target. Selectors tied to nesting, generated classes, or other implementation details can break during harmless markup refactors. If a selector matches multiple elements, narrow it with a role, text, attribute, or an appropriate locator filter before calling evaluate().

Rank #2
Philips 22 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 221V8LB
  • 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

Verify the mutation

Use a web-first assertion

await expect(button).toHaveAttribute('data-state', 'ready');

toHaveAttribute() waits and retries until the locator points to an element with the expected attribute value or the test timeout is reached. This is preferable to immediately reading the DOM after an action because a page may update asynchronously.

Read an attribute without asserting

const value = await button.getAttribute('data-state');
console.log(value);

getAttribute(name) retrieves the current value and returns null when the attribute is absent. It is a read operation, not a setter; use evaluate() and setAttribute() to change the DOM.

Check only presence

await expect(button).toHaveAttribute('aria-busy');

When you need to confirm that an attribute exists but do not care about its value, assert the attribute name without an expected value.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Complete examples

Set an ARIA-related attribute for a DOM-level test

test('marks a panel as busy', async ({ page }) => {
  const panel = page.getByRole('region', { name: 'Results' });

  await panel.evaluate((element) => {
    element.setAttribute('aria-busy', 'true');
  });

  await expect(panel).toHaveAttribute('aria-busy', 'true');
});

This example demonstrates the API only. In a real application, accessibility state should normally be produced by the application’s supported interaction or state update, then observed by the test.

Set several attributes in one page callback

await page.getByTestId('card').evaluate((element) => {
  element.setAttribute('data-status', 'ready');
  element.setAttribute('data-version', '2');
});

const card = page.getByTestId('card');
await expect(card).toHaveAttribute('data-status', 'ready');
await expect(card).toHaveAttribute('data-version', '2');

Use this when the attributes are one atomic DOM setup operation. For tests of user behavior, prefer the user action that naturally causes the application to set those attributes.

Rank #3
Sale
Dell 24 Monitor - SE2426H - 23.8-inch FHD (1920x1080) 144Hz 1ms Display, in-Plane Switching (IPS) Technology, AMD FreeSync™, TÜV 3-Star 2X HDMI, Tilt
  • 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.

setAttribute() versus Playwright actions

Goal Preferred API Reason
Change an arbitrary DOM attribute locator.evaluate() with setAttribute() Runs the DOM mutation in page context.
Enter text in an input locator.fill(value) Models the supported input operation and associated Playwright behavior.
Click a control locator.click() Exercises the interaction rather than bypassing it.
Check an attribute expect(locator).toHaveAttribute() Waits and retries as the page settles.
Read an attribute for branching or logging locator.getAttribute() Returns the current value without changing it.

Do not use an attribute mutation as a substitute for an application action when the attribute represents framework-managed state. A direct DOM change may be overwritten by the next render, may not update the component’s internal state, and may not trigger the events your application expects. The reviewed Playwright API documentation does not establish automatic framework synchronization for this mutation.

Common failures and fixes

“Locator resolved to multiple elements”

Cause: the locator is ambiguous. Fix: improve the accessible name, use a test ID, or apply a deliberate filter. Avoid selecting the first match merely to hide a locator defect.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

“Element is not found” or a timeout

Cause: the element is not rendered, the locator is wrong, or the page is on a different state than expected. Fix: wait for the application state that creates the element, verify the role/name in the Playwright inspector, and check that navigation completed before evaluating.

The assertion sees the old value

Cause: application code re-rendered the element after your mutation and replaced the attribute. Fix: perform the supported UI or application-state operation, then assert the resulting attribute. If the test intentionally edits the DOM, make the mutation after the final render and assert immediately.

The callback cannot access Node.js variables

Cause: the callback runs in the browser context. Fix: pass data through the second evaluate() argument.

Rank #4
Samsung 27" Essential S3 (S36GD) Series FHD 1800R Curved Computer Monitor
  • 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
const expected = 'ready';
await button.evaluate(
  (element, value) => element.setAttribute('data-state', value),
  expected,
);

The attribute is present but the value is unexpected

Cause: HTML attributes are string values, or application code normalized/replaced the value. Fix: pass the exact string expected by the page and assert that exact string. For a missing attribute, remember that getAttribute() returns null.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The mutation appears to do nothing

Cause: CSS may not react to the attribute, the selected element may not be the one visible to the user, or a framework may immediately render over it. Fix: inspect the matched element, assert the attribute, and test the application’s supported pathway when behavior—not just markup—is the requirement.

Reliability and maintainability checklist

  • Use a role/name locator or an explicit test ID where possible.
  • Confirm the locator identifies one intended element.
  • Keep dynamic values in the evaluation argument rather than interpolating them into selector strings.
  • Use toHaveAttribute() for verification instead of an immediate, timing-sensitive read.
  • Use fill(), click(), and other Playwright actions for ordinary user interactions.
  • Separate a DOM-focused unit of setup from assertions about framework state or user-visible behavior.
  • Check the API documentation for the Playwright version used by your project, because documentation and behavior can change between versions.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your goal is to obtain a clean image or PDF of a page rather than mutate its DOM in a test, ScreenshotNeo provides a single website-screenshot API request. It accepts consent banners as a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the result with X-Page-Verdict and X-Billed headers. It also offers an MCP server for AI agents, with take_screenshot, get_page_info, and capture_pdf tools.

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 service supports PNG, JPEG, WebP, and PDF output; full-page and element captures; device presets and custom viewports; retina scale; dark mode; custom CSS and JavaScript; waits; clicks; hidden selectors; blocked ads, trackers, requests, and resource types; headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, chosen cache TTLs, signed links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, a usage API, and an OpenAPI specification. Parameter names used by other screenshot APIs also work for easier migration.

The Free plan includes 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 screenshots; every feature is included on every plan, and yearly billing gives two months free. Sign up free for ScreenshotNeo.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

FAQ

Does setAttribute() trigger a click or input event?

No. It changes the DOM attribute. It does not model a user interaction; use the corresponding Playwright action when event behavior is what you are testing.

Best Value
Sale
Sceptre New 22-Inch Gaming Monitor, FHD 1080p, Up to 144Hz, HDMI, DisplayPort, Built-in Speakers, Machine Black (E225W-FW144 Series, 2026)
  • 【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.

Can I remove an attribute instead?

Yes. Run element.removeAttribute('data-state') inside locator.evaluate(), then assert absence with an attribute assertion appropriate to your test.

Will the change survive navigation?

No. A page-context DOM mutation belongs to the current document and is lost when that document is replaced or reloaded.

Frequently Asked Questions

Does setAttribute() trigger a click or input event?

No. It changes the DOM attribute. It does not model a user interaction; use the corresponding Playwright action when event behavior is what you are testing.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Can I remove an attribute instead?

Yes. Run element.removeAttribute('data-state') inside locator.evaluate(), then assert absence with an attribute assertion appropriate to your test.

Will the change survive navigation?

No. A page-context DOM mutation belongs to the current document and is lost when that document is replaced or reloaded.

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.