Is there any way to select (i.e. create locators) by style value

ghz 8months ago ⋅ 69 views

In Playwright there are a lot of ways to create locators, mostly involving CSS selectors. However, as far as I can tell, there's no way to say "find the red button" (i.e. the <button> with background-color: red).

If the button has a red class, then of course you can select .red, but what if you don't have a class? If you only care about certain styles (e.g. display) you can use special Playwright selectors (e.g. :visible), but they only work for those specific styles.

Is there any general purpose way to find elements based on any style value?

Answers

As of my last update, there isn't a direct, built-in way in Playwright to locate elements based on their style attributes/values such as background color. Playwright primarily relies on CSS selectors, which don't provide a way to directly query elements based on their computed styles.

However, you can achieve this indirectly by using JavaScript evaluation within Playwright. You can execute JavaScript code in the context of the page to find elements based on their computed styles. Here's a basic example of how you could accomplish this:

const elementHandle = await page.evaluateHandle(() => {
    // Find all buttons on the page
    const buttons = document.querySelectorAll('button');
    
    // Iterate through each button and check its computed style
    for (const button of buttons) {
        const computedStyle = window.getComputedStyle(button);
        
        // Check if the button has a red background color
        if (computedStyle.backgroundColor === 'red') {
            return button;
        }
    }
    
    // Return null if no matching button is found
    return null;
});

// Use the element handle returned by the JavaScript evaluation
if (elementHandle) {
    // Do something with the element
} else {
    // Handle case when no matching button is found
}

In this code:

  • evaluateHandle executes the provided JavaScript function in the context of the page and returns a handle to the result.
  • Inside the JavaScript function, querySelectorAll is used to find all buttons on the page.
  • Then, getComputedStyle is used to get the computed style of each button, and it's checked if the background color is red.
  • If a matching button is found, it's returned; otherwise, null is returned.

You can integrate this approach into your Playwright scripts to locate elements based on their styles. Keep in mind that this method might not be as efficient as using native CSS selectors, especially if you're querying a large number of elements or if performance is critical.