Retrieve a list of class names associated with a Playwright element

Can anyone suggest the best method to retrieve an array of all class names for an element in Playwright using TypeScript?

I've searched for an API but couldn't find one, so I ended up creating the following solution:

export const getClassNames = async (locator: Locator): Promise<string[]> => {
    // Ensure we have exactly one element
    await expect(locator).toHaveCount(1);

    // Get the element
    const element = locator.first();

    // Use evaluateHandle to obtain an array of class names for the element
    const classListHandle = await element.evaluateHandle((el: Element) => Array.from(el.classList));

    // Extract the class names from the classListHandle
    const classNames = await classListHandle.jsonValue() as string[];

    return classNames;
};

Answer №1

At this moment, there doesn't seem to be a function available for this specific task. However, you can significantly reduce the length of your code:

export const getClassNames = (locator: Locator): Promise<string[]> =>
  locator.evaluate(el => [...el.classList]);

If you are operating in strict mode, the .evaluate method already confirms that there is only one element present, eliminating the need for ElementHandles which Playwright generally advises against using.

Here is a sample demonstration that can be executed:

const playwright = require("playwright"); // 1.30.0

const classList = loc => loc.evaluate(el => [...el.classList]);

let browser;
(async () => {
  browser = await playwright.chromium.launch();
  const page = await browser.newPage();

  await page.setContent(`<p class="a b c"></p>`);
  console.log(await classList(page.locator("p"))); // => [ 'a', 'b', 'c' ]

  await page.setContent(`<p></p><p></p>`);
  console.log(await classList(page.locator("p")));
    // => strict mode violation: locator('p') resolved to 2 elements
})()
  .catch(err => console.error(err))
  .finally(() => browser?.close());

However, if your intent is to use this for a testing assertion, consider using

await expect(locator).toHaveClass(["some", "classes"]);

as specified in this answer instead.

Answer №2

When verifying an element's classes, a tidy approach is to use the following code:

const locator = page.locator('list > .component');
await expect(locator).toHaveClass(['component', 'component selected', 'component']);

You can also utilize regular expressions like this:

await expect(locator).toHaveClass(/selected/);

For more information, check out:

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

Typescript: The ConstructorParameters type does not support generics

Incorporating TypeScript 3.7, I created an interface featuring a property designed to accept a constructor function: interface IConstruct<T> { type: new (...args:ConstructorParameters<T>) => T; } I initially assumed that IConstruct<Us ...

Typescript's Intersection Types: The Key to Overlapping Properties

Looking to create a type-safe utility function in Typescript 4.0 for comparing properties of two objects, my initial code snippet is below: export function propertiesMatch<O extends object, T extends O, S extends O>(first: T, second: S, props: (keyof ...

Should I opt for ionic2 for my production needs?

Currently, I am using Ionic 1 and AngularJS 1 for our applications. We are considering transitioning to Ionic 2 for our new applications. Is this the right decision? I have a few questions: AngularJS 1 and Angular 2 are different, but how does Ionic ...

Is Typescript capable of converting ES6 code to ES5 during transpilation?

Currently, I'm in the process of developing an application utilizing Angular 2 and TypeScript. My goal is to incorporate a JavaScript method, specifically 'filter' for arrays, that is compatible with IE 11+, Chrome 45+, and other similar bro ...

Encountering TypeScript errors while trying to implement Headless UI documentation

import { forwardRef } from 'react' import Link from 'next/link' import { Menu } from '@headlessui/react' const MyLink = forwardRef((props, ref) => { let { href, children, ...rest } = props return ( <Link href={href}&g ...

Error in cypress configuration occurs when a plug is mistakenly defined as an import instead of a const within the cypress.config.ts file

Hello, I am new to using Cypress so please bear with me if this seems like a trivial issue. Below you will find my cypress.config.ts file where I am attempting to integrate the cypress esbuild preprocessor into the configuration. import cypress_esbuild_pre ...

I'm looking for a way to modify the Turkish characters and spaces in the names of JSON data objects. I plan to do this using WebApi

I am facing an issue with fetching data through an API. The JSON data format contains Turkish characters and spaces, causing problems when trying to display the data in a datatable. I have attempted to use the replace and parse functions, but so far, I hav ...

Module augmentations do not allow for exports or export assignments

import { Request as ExpressRequest, Response as ExpressResponse } from 'express'; declare module 'kvl' { export = kvl; } declare const kvl: { ValidationDone:(param:(error: any, response: ExpressResponse) => void) => void; ...

Exploring the process of introducing a new property to an existing type using d.ts in Typescript

Within my src/router.ts file, I have the following code: export function resetRouter() { router.matcher = createRouter().matcher // Property 'matcher' does not exist on type 'VueRouter'. Did you mean 'match'? } In an ...

In the d.ts file, Typescript simply creates the line "export {};"

After executing the tsc command to compile my project into the dist directory, I noticed that typescript is generating an incorrect or empty d.ts file. Here is a snippet of my tsconfig.json: { "compilerOptions": { "module": " ...

The geolocation feature is operational in the browser test, but it is not functioning properly on the

I am currently creating an application that requires accessing the user's location at a specific point in time. To achieve this, I have utilized the ionic native geolocation feature which communicates with the Google API for reverse geocoding. Everyt ...

'This' loses its value within a function once the decorator is applied

Scenario: Exploring the creation of a decorator to implement an interceptor for formatting output. Issue at Hand: Encountering 'this' becoming undefined post application of the decorator. // custom decorator function UseAfter(this: any, fn: (.. ...

Secure a reliable result from a function utilizing switch statements in Typescript

There's a function in my code that takes an argument with three possible values and returns a corresponding value based on this argument. Essentially, it can return one of three different values. To achieve this, I've implemented a switch statem ...

Typescript: Omitting mandatory fields from a type

Can anyone help me with defining the type ExcludeAllRequiredProps<T> in the code below to exclude all required properties? Any assistance would be greatly appreciated. Thank you. type A = { a: number, b: number, c?: number, d?: number } typ ...

What is the method for adding a document within an array that is nested within another document?

Apologies if the title seems complex... I struggled to find a better way to describe it. The scenario I am dealing with fits the following Schemes: Collection1: const mongoose = require('mongoose'); const itemSchema = mongoose.Schema({ _id: ...

Tips for sorting through the state hook array and managing the addition and removal of data within it

Having trouble finding a solution for filtering an array using the React useState hook? Let me assist you. I have declared a string array in useState- const [filterBrand, setFilterBrand] = useState<string[]>([]); Below is my function to filter this ...

enhancing the types of parameters in a function declaration without relying on generics

My goal is to improve developer experience (DX) by expanding the types for parameters in a function signature. I want the tooltip when hovering over the following function to provide more detailed information: type Props = { a: number; }; const func = ( ...

Iterating over a JSON array using *ngFor

Here is the JSON structure that I have: { "first_name": "Peter", "surname": "Parker", "adresses": { "adress": [{ "info1": "intern", "info2": "bla1" }, { "info1": "extern", "info2": "bla2" }, { "info1": " ...

Only the final defined document is instantiated by the Swagger-ui-express module

Currently, I am working on a Typescripted nodejs server and facing an issue with defining different swagger paths for separated controllers. The problem is that the swagger-ui-express module only displays the last defined document in the specific route. I ...

The variable ApiAIPromises is not recognized within the context of Ionic 3 and Dialogflow

I am currently integrating dialogflow into my ionic app. Below is the code snippet from my .ts file: import { Component, NgZone } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; declare v ...