Switch to v2 to see which selectors break.
Add to Chrome

SVG and canvas practice

Practice locating SVG icons and chart bars, an SVG inside a shadow root, and tiles drawn on a canvas, where there is no DOM to find at all.

SVG icon button

Built well

Built to break

SVG bar chartClick Wednesday’s bar.

Built well

Mon: 12 ordersTue: 19 ordersWed: 7 ordersThu: 15 ordersFri: 22 orders

Built to break

CanvasClick the green tile.

Built well

Built to break

SVG inside a shadow root

Built well

Built to break

How to locate SVG and canvas

SVG is a different namespace; canvas is not DOM at all

SVG elements live in their own XML namespace, so an XPath like //svg or //rect finds nothing in an HTML page. XPath has to match by name: //*[name()="svg"] or //*[local-name()="rect"]. CSS selectors don’t have this problem; svg rect works as written.

Icon buttons are the common case. When the clickable thing is a bare <svg> with a click handler, there is no role and no name, just a path. A well-built icon button wraps the SVG in a <button> with an aria-label, and the SVG becomes decoration.

Charts drawn in SVG are made of rect, path and circle elements that look identical. Without a test id or a <title>, the only way to pick a bar is its position, which changes as soon as the data does.

Canvas is different again. Whatever is drawn on it is pixels: there are no elements inside to find. A test can locate the <canvas> itself and click at coordinates, which breaks with any layout change. Pages built with testing in mind offer an accessible equivalent, like the buttons under the good canvas here.

What a stable locator looks like

For icons, target the button by its accessible name. For SVG in XPath, match with name() or local-name(), or switch to CSS. For charts, use test ids or titles on each shape. For canvas, prefer the page’s accessible controls; click by coordinates only as a last resort.

await page.getByRole('button', { name: 'Delete item' }).click();
await expect(page.getByTestId('svg-delete-result')).toHaveText('Deleted');

// XPath needs name() or local-name() for SVG elements
await page.locator('//*[name()="svg"][@data-testid="sales-chart"]/*[name()="rect"][@data-testid="bar-wed"]').click();
await expect(page.getByTestId('chart-result')).toHaveText('Wed: 7 orders');

// Canvas: use the accessible buttons, or click by coordinates
await page.getByRole('button', { name: 'Green' }).click();
await page.getByTestId('tiles-canvas').click({ position: { x: 110, y: 40 } });
await expect(page.getByTestId('canvas-result')).toHaveText('Green tile');

In a real workflow

Icon-only buttons, charts and canvas widgets turn up in every admin and dashboard. The same rules apply there: name the button, label the shape, and offer controls that don’t need coordinates.

COR Lens generates locators for shadow DOM, iframes and tables, and grades each one. Click the svg and canvas above with it and compare its pick with yours.

Add to Chrome