JohnN
JohnN

Reputation: 1010

Using querySelector for child elements

I've been using JavaScript for a few years writing scripts for automated tests for Desktop applications. However, I've recently transitioned into writing automated tests for web applications using Playwright. I've had to learn how to work with the html/css selectors. One thing that's eluded me is if there is a way (I feel like there must be) to specify an element on a page using a parent element and then the child element.

For example, I've got a pop up window which is a basic login page with ID and password. The textboxes for id and password do not have unique properties to point to, just <input type="text">. However, the entire login has the class of "page-options" which I know i can just grab with document.querySelector('.page-options');. Is there a way I can reference the inputs using await page.fill(); from playwright?

<div class="page-options">
    <div>
        <label>Page ID</label>
        <input type="text">
    </div>
    <div>
        <label>Page Password</label>
        <input type="text">
    </div>
</div>

Upvotes: 1

Views: 853

Answers (2)

Nora
Nora

Reputation: 149

Use the label text to id the required input:

await page.locator('text="Page ID" >> .. >> input').fill('name');  // label >> parent >> input
await page.locator('text="Page Password" >> .. >> input').fill('secret');

const value = await page.locator('text="Page Password" >> .. >> input').inputValue()  
expect(value).toEqual('secret')  

Upvotes: 2

Alapan Das
Alapan Das

Reputation: 18650

You can do something like this using the N-th element selector:

//For username
await page.locator('input[type="text"] >> nth=0').fill('value');

//For password
await page.locator('input[type="text"] >> nth=1').fill('value');

Upvotes: 0

Related Questions