Tips for choosing an HTML element using Playwright with TypeScript

My goal is to use playwright with typescript in order to select a specific html element. The element I am trying to target has the class "ivu-select-dropdown" and a specific style.

<div class="ivu-select-dropdown" style="position: absolute; min-width: 180px; will-change: top, left; transform-origin: center top; top: 135px; left: 339px;" x-placement="bottom-start">
       <ul class="ivu-select-not-found" style="display: none;">
            <li>No matching data</li>
        </ul>
        <ul class="ivu-select-dropdown-list">
            <li class="ivu-select-item">
                <div class="custom-select-item-for-preview">5Cells</div>
            </li>
            ... and other li elements

I have tried referencing the documentation but I am still unsure how to properly utilize the class "ivu-select-dropdown" for targeting this element.

The html structure of the page seems to be dynamic and it may also include the following structure before any actions are taken:

<div class="custom-autocomplete-targets ivu-select ivu-select-single ivu-select-small ivu-form-item-error">
    <div tabindex="-1" class="ivu-select-selection"><input type="hidden">
        <div class="">
            <!---->
            <!----> <span class="" style="display: none;"></span> <input type="text" placeholder="Select" autocomplete="off" spellcheck="false" class="ivu-select-input">
            <!----> <i class="ivu-icon ivu-icon-ios-arrow-down ivu-select-arrow"></i></div>
    </div>
    <div class="ivu-select-dropdown" style="display: none; position: absolute; min-width: 180px; will-change: top, left; transform-origin: center top; top: 135px; left: 339px;" x-placement="bottom-start">
        <ul class="ivu-select-not-found" style="display: none;">
            <li>No matching data</li>
        </ul>
        <ul class="ivu-select-dropdown-list">
            <li class="ivu-select-item">
                <div class="custom-select-item-for-preview">5Cells</div>
        </li>
        ... and other li elements

Answer №1

Finding an element with specific text using CSS selectors can be challenging, but XPath makes it much simpler:

let dropDownItem = page.locator("xpath=//li[@class='ivu-select-item']/div[text()='5Cells']");
await dropDownItem.click();

If you prefer to click on the li element instead of the nested div, you can use this selector:

let dropDownItem = page.locator("xpath=//li[@class='ivu-select-item']/div[text()='5Cells']/parent::li");

You can test this with the following mock HTML structure:

<html>

<body>
  <h1>Mock</h1>
  <div class="ivu-select-dropdown" style="position: absolute; min-width: 180px; will-change: top, left; transform-origin: center top; top: 50px; left: 50px;" x-placement="bottom-start">
    <ul class="ivu-select-not-found" style="display: none;">
      <li>No matching data</li>
    </ul>
    <ul class="ivu-select-dropdown-list">
      <li class="ivu-select-item">
        <div class="custom-select-item-for-preview">3Cells</div>
      </li>
    </ul>
    <ul class="ivu-select-dropdown-list">
      <li class="ivu-select-item">
        <div class="custom-select-item-for-preview">5Cells</div>
      </li>
    </ul>
  </div>
</body>

</html>

Answer №2

Hey there Alex!

Give this a try:</p>

If you open up your browser and use the devtools, you can easily change the index to access different elements:

(//li[@class='ivu-select-item'])[1]

or

(//li[@class='ivu-select-item'])[2]

and so on...

(//li[@class='ivu-select-item'])[X]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a randomly generated array within a Reactjs application

Every time a user clicks a button in reactjs, I want to create a random array of a specific size. The code for generating the array looks like this: const generateArray = (arraySize: number): number[] => { return [...Array(arraySize)].map(() => ~~( ...

Adding types to computed properties in Vue 3's Composition API is a seamless process

Having an issue where I am trying to add type to computed but keep encountering this error: Overload 1 of 2, '(getter: ComputedGetter<AuthFormType>, debugOptions?: DebuggerOptions | undefined): ComputedRef<AuthFormType>', gave the fol ...

Transferring data from two child components back to the parent component

Within my web application, I have a parent component (A) and two children components (B, C). The parent component is responsible for maintaining the basic layout of the page, which remains consistent across all layouts. However, I need to dynamically swap ...

The declaration module in Typescript with and without a body

I am facing an issue with importing a .mdx file. When I include the following in my mdx.d.ts: /// <reference types="@mdx-js/loader" /> import { ComponentType } from "react"; declare module '*.mdx' { const Component: ...

Passing variables from a template to TypeScript using ngFor

Need help passing a variable from a template to typescript using *ngFor loop. Currently, my code looks like this: <select (change)="onregionchange()" data-placeholder="Regions" class="form-control regions-select" id="regions" multiple> <opt ...

Using TypeScript to Load JSON Data from a Folder

I'm a newcomer to TypeScript and encountering an issue. My task involves dynamically loading objects from a directory that houses multiple JSON files. The file names are generated through an export bash script populating the resource directory. I wan ...

Define a module function that can be used externally

I am encountering an issue while trying to declare an external module that does not have existing typings. This library has a function that returns a string and takes no arguments. My attempt to define it in a .d.ts file is as follows: declare module "c ...

A comprehensive guide on extracting data from the query string in Angular

There is a specific query string format that we need to handle. The input parameter of the method comes in the form of a string and it's not an instance of ActivatedRoute. http://localhost:4200/users?param1=en&param2=nk I've attempted to rea ...

Group records in MongoDB by either (id1, id2) or (id2, id1)

Creating a messaging system with MongoDB, I have designed the message schema as follows: Message Schema: { senderId: ObjectId, receiverId: ObjectId createdAt: Date } My goal is to showcase all message exchanges between a user and other users ...

Prevent selection of future dates and display them in a muted grey color in the p-calendar component

I am attempting to prevent users from selecting future dates and visually distinguish them by setting a grey color background. However, I am having trouble disabling the future dates while the grey color background is functioning correctly. Any ideas on ho ...

The declaration file for the datepicker module could not be located, even though the necessary types have been installed

I'm encountering an issue during production build on my Next.js project. The error message reads: Could not find a declaration file for module 'react-datepicker'. '../node_modules/react-datepicker/dist/index.js' implicitly has an ...

Encountering a 500 error code while attempting to send a post request using Angular

Whenever I attempt to send a post request to Django server, I encounter a 500 (Internal Server Error) response. Interestingly, the get and put requests work flawlessly on the same server where Django is connected to PostgreSQL database. Here is a snippet ...

The use of p-message in Angular's PrimeNg library is not permitted

Hey there, I'm having a bit of trouble with the p-message Tag in Angular. I believe I've imported it correctly as shown below. import { MessageModule } from 'primeng/message'; imports: [ .... MessageModule, ... In the ...

What is the best way to transform private variables in ReactJS into TypeScript?

During my conversion of ReactJS code to TypeScript, I encountered a scenario where private variables were being declared in the React code. However, when I converted the .jsx file to .tsx, I started receiving errors like: Property '_element' d ...

Is it possible to deduce the output type of a function based on its input?

In a web development project, the function getFormData() plays a crucial role in validating and sanitising a FormData object based on a specified schema. If the validation process goes smoothly without any errors, the function will return the cleansed Form ...

Tips for maintaining the original data type while passing arguments to subsequent functions?

Is there a way to preserve generic type information when using typeof with functions or classes? For instance, in the code snippet below, variables exampleNumber and exampleString are of type Example<unknown>. How can I make them have types Example& ...

What is the best way to accurately parse a Date object within a TypeScript class when the HttpClient mapping is not working correctly?

Task.ts: export class Task { name: string; dueDate: Date; } tasks.service.ts: @Injectable() export class TasksService { constructor(private http: HttpClient) { } getTasks(): Observable<Task[]> { return this.http.get<Ta ...

Utilizing a React hook to render and map elements in a function

Can the hook return function be assigned to a render map in React? In this example, we have the socialAuthMethodsMap map with the onClick parameter. I tried to assign the signInWithApple function from the useFirebaseAuth hook, but it violates React's ...

Issue with importing and exporting external types causing failures in Jest unit tests for Vue 2

I am in the process of creating a package that will contain various types, enums, consts, and interfaces that I frequently use across different projects. To achieve this, I have set up a main.ts file where I have consolidated all the exports and specified ...

Include type declarations for property values that resemble arrays in a generic object

Imagine you have a function that: receives an object with multiple properties and a property name; checks if the property holds an array; if it does, performs an action (such as printing the values it contains) Here's an illustration: function pro ...