Reputation: 511
Using Playwright, I'd like to find an element using the value of a variable
For example:
let name = 'Sully'
await page.click(`li:has-text(${sully})`)
but I get the following error:
page.click: Error: "has-text" engine expects a single string
Upvotes: 3
Views: 6415
Reputation: 4171
These are not recommended by playwright docs anymore.
"XPath and CSS selectors can be tied to the DOM structure or implementation. These selectors can break when the DOM structure changes. Long CSS or XPath chains can lead to unstable tests."
Page.click
is also discouraged.
In comparison, locators are dynamic and don't depend on page structure.
let name = 'Sully'
await page
.getByRole('listitem')
.filter({ hasText: name})
.click();
Upvotes: 2
Reputation: 8652
You have to add single or double quotes to the has-text
function and use the name
variable instead of sully
or declare it.
Hence, it should be like this:
let name = 'Sully';
// ↓ ↓ - missed quotes
await page.click(`li:has-text('${name}')`)
Upvotes: 9