Rayrun

How does Playwright handle spaces in class names when using them as locators?

Answer

Handling Spaces in Class Names with Playwright

Yes, you can exclude any space in class names when using them as locators in @playwright/test. Playwright normalizes whitespace when matching elements with CSS selectors. This means it turns multiple spaces into one, line breaks into spaces, and ignores leading and trailing whitespace.

Here's an example. If you have an element with the class name "my-class", you can use the CSS selector css=.my-class to locate it. The space between the dot (.) and the class name isn't necessary for matching.

const element = await page.$('css=.my-class');

Playwright also supports other locators like id, data-testid, data-test-id, and data-test selectors. You can use these to select elements based on specific attributes. For instance, you can use id=username to locate an input element with the id "username".

const usernameInput = await page.$('id=username');

Remember, attribute selectors in Playwright aren't CSS selectors. So, CSS-specific features like :enabled aren't supported when using attribute selectors. If you need more advanced features, use proper CSS selectors.

You can also chain locators for more complex queries. Selectors defined as engine=body or in short-form can be combined using the >> token. This lets you query elements relative to previous results.

const nestedElement = await page.$('css=.parent >> css=.child');

In short, you can exclude any space in class names and still locate elements using CSS selectors or other supported attributes. Chaining locators lets you query elements relative to previous results for more complex queries.

References

Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

Related Discord Threads

Related Questions

TwitterGitHubLinkedIn
AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email [email protected].