Rayrun
← Back to Discord Forum

Exclude space in class locators

Can we exclude any space that is there in the class name and use them as locators?

For example, if a class name is "style visible", can we use just "style" as a locator?

I am asking this because sometimes my playwright works with "style" and sometimes with "style ".

This thread is trying to answer question "Can we exclude any space that is there in the class name and use them as locators?"

0 replies

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.

Related Discord Threads

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].