最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is it possible to get current selected text in Playwright JS select dropdown? - Stack Overflow

programmeradmin3浏览0评论

I can set value in the select dropdown. But when I call textContent, it returns all options values. My task is to verify that the set value is selected properly by extracting the value and checking it.

Is there any support for it in Playwright JS?

I tried different solutions.

One of them is below, but it didn't work

const selectedOptionText = await page.$eval(
  `${selector_value_here} option:checked`,
  (option) => option.textContent
);

console.log('Selected option text:', selectedOptionText);

I can set value in the select dropdown. But when I call textContent, it returns all options values. My task is to verify that the set value is selected properly by extracting the value and checking it.

Is there any support for it in Playwright JS?

I tried different solutions.

One of them is below, but it didn't work

const selectedOptionText = await page.$eval(
  `${selector_value_here} option:checked`,
  (option) => option.textContent
);

console.log('Selected option text:', selectedOptionText);
Share Improve this question edited Sep 17, 2023 at 15:22 Anton Kesy 8262 gold badges11 silver badges18 bronze badges asked Sep 17, 2023 at 15:11 MukhaMukha 3131 gold badge3 silver badges8 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

To get the selected value from dropdown:

For example, if your HTML is:

<select id="my-dropdown">
  <option value="option1">Option 1</option>
  <option value="option2" selected>Option 2</option>
  <option value="option3">Option 3</option>
</select>

You can retrieve the selected value like this:

const selectedValue = await page.locator('#my-dropdown').evaluate(select => select.value);
console.log(selectedValue); // Output: "option2"

To validate selected value:

const dropdown = page.locator('#my-dropdown');
await expect(dropdown).toHaveValue('Option 2')

You may use evaluate https://playwright.dev/python/docs/next/api/class-worker#worker-evaluate

locator.evaluate("el => el.options[el.selectedIndex].text")

发布评论

评论列表(0)

  1. 暂无评论