Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with CSS locator select-react

Tags:

java

css

selenium

I have an issue with a CSS locator. I have a unique label for the parent, and from there I can get the child that I need.

@FindBy(css = "[data-qa="select-Seller"] .select__value-container")
Webelement seller;
public Webelement getSeller(){ return seller; }

The class is similar to all dropdowns, so the only value that will change is data-qa. Also, sometimes I need to deselect them.

For that, I have an X locator.

@FindBy(css = "[data-qa="select-Seller"] [data-qa=icon-x]). 

As you can see, the first part is still the same.

So my question is is it possible to write some method (or any other way) that will change the last part of the locator? I have 600+ dropdowns and creating 600+ new locators for an X will make me go nuts.

For me, the best way to do something like element.click\sendkeys\...\ uses the default part (with .select__value-container), but if I will write something like element.deselect then it will change the locator, but I don't know how.

I wrote something like this:

public void clearDropdown (WebElement element){
        String selector = element.toString();
        selector = selector.split(" ")[8];
        driver.findElement(By.cssSelector(selector + " [data-qa=icon-x]")).click();
    }

[[ChromeDriver: chrome on MAC (99c7e4e38147c9f61da0c83c5ef1b992)] -> css selector: [data-qa='select-Seller'] .select__value-container] - this is why "split(" ")[8]"

But I don't think that this is the right way to solve the issue.

Thank you for your suggestions.

like image 997
Dmytro Ivanenko Avatar asked Jun 08 '26 10:06

Dmytro Ivanenko


1 Answers

You don't have to try to concatenate CSS selectors.

It would be easier if you could define a parent as a WebElement:

WebElement seller = driver.findElement(By.cssSelector("[data-qa=select-Seller]"));

And then find elements inside it:

WebElement sellerDropdown = seller.findElement(By.cssSelector(".select__value-container"));

WebElement closeButton = seller.findElement(By.cssSelector("[data-qa=icon-x]"));

Note how we are using seller.findElement instead of driver.findElement for child elements.


I am not 100% sure how to describe this in FindBy terms, take a look if this helps:

  • Selenium/PageFactory: Find child elements using parent element's @FindBy?
like image 190
alecxe Avatar answered Jun 10 '26 18:06

alecxe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!