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;
};