Unable to locate the sibling element using CSS Selector with Selenium

When using a CSS Selector to click on the next sibling element in Selenium WebDriver, an InvalidSelectorException is thrown.

If we consider my DOM structure:

<div class="checkbox-group">
   <div>     
       <span class="checkbox">::after</span> <!--clicking on this span checks the checkbox-->
       <span class="checkbox-name">Male</span> <!--clicking on this span does not check the checkbox-->
   </div>
   <div>
      <span class="checkbox">::after</span>
      <span class="checkbox-name">Female</span>
   </div>
</div>

Here is the Java code snippet:

@FindAll(@FindBy(css=".checkbox-name"))
List<WebElement> checkboxes;

public void selectCheckbox(String value){
    for(WebElement checkbox : checkboxes){
        String text = checkbox.getText();
        if(text.equalsIgnoreCase(value)){
            WebElement control = checkbox.findElement(By.cssSelector("+.checkbox"));//The exception occurs here     
            control.click();
        }
    }
}

The Exception message states:

org.openqa.selenium.InvalidSelectorException: invalid selector: An invalid or illegal selector was specified. 
** Element info: {Using=css selector, value=+.checkbox} 

Answer №1

Instead of searching for the element with the class checkbox-name and verifying if it contains the String value, you can streamline the process by directly locating that element using the text attribute in the xpath.
Once you have identified the element, you can utilize the following-sibling axis in the xpath to access the adjacent span element which can be clicked.

All of this can be achieved using a single xpath query:

public void selectCheckbox(String value){
    WebElement checkBox = driver.findElement(By.xpath("//div[@class='checkbox-group']//span[text()="+value+"]//following-sibling::span"));
    checkBox.click();
}

Answer №2

While some may suggest using xpath to solve this problem easily, it's important to note that I already have that solution in place. The real question here is why selenium isn't functioning correctly even with the correct CSS selector.

Xpath approach:

public void chooseCheckbox(String value){
    for(WebElement checkbox : checkboxes){
        String text = checkbox.getText();
        if(text.equalsIgnoreCase(value)){
            WebElement control = checkbox.findElement(By.xpath("./parent::div/span[@class='checkbox']"));
            control.click();
        }
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What causes the source code of a website to change when accessed from various browsers?

When analyzing the source code of bartzmall.pk using various browsers, it reveals different classes being added to the html tag for each browser. For Firefox: <html class="firefox firefox53 otherClasses"> For Chrome: <html class="webkit chrome ...

Troubleshooting issue with Selenium WebDriver and Chrome version 117

I've encountered an issue while using the Python Chrome web driver with Selenium. Here is the code that was previously working but stopped after updating to Chrome version 117: from selenium import webdriver from selenium.webdriver.common.keys import ...

Closing the space between navigation bar choices

I'm currently working on my website's navbar menu and struggling to eliminate the gap between each of the navbar links. It seems that the li attributes with the class dropdown are slightly wider than the rest of the links, causing this issue. I&a ...

Navigating Inconsistent Modals with Selenium Python Bindings

I'm currently facing an issue while filling out a form on a website that adapts its versions based on different factors like language and location. I am using the same Firefox profile for all requests, and the previously selected information is stored ...

Attaching a buoyant div to the precise location of a different element

I have a unordered list (ul) with individual list items (li) that are displayed within a scrollable container. This means that only 8 list items are visible at a time, but you can scroll through them to see the others. Each list item (li) has an "edit" b ...

I'm experiencing issues with my code involving HTML, CSS, and jQuery

Recently, I started learning about jQuery and came across a tutorial on creating a sticky nav bar. However, something went wrong during the implementation and now I don't know how to fix it! In my Script file, I have written code that should run on l ...

What could be causing the slow start to my feature tests using Rails, Selenium, and Spring?

My Rails 5.0.5 application has feature tests that utilize Capybara and Selenium with chromedriver. Despite using spring, the first request to my app during the feature tests takes around 45 seconds before subsequent requests return to normal response times ...

Using CSS to position elements absolutely while also adjusting the width of the div

In one section of my website, I have a specific div structure. This structure consists of two divs stacked on top of each other. The first div is divided into two parts: one part with a width of 63% and another part with a button. Beneath the first div, t ...

the mobile website is not properly aligned on a horizontal axis

As I work on creating a mobile version of my website, I've come across a challenge: The entire site fits perfectly on the computer at a browser width of 480px, but when viewed on my mobile phone (regardless of the browser used), it leaves space on the ...

Avoid stretching the div to the edge of the screen

In the table on my page, I have implemented a feature using CSS to display additional information in a popup div. This works well when there is limited text, but if there is extensive text in the table, it extends beyond the screen width and becomes diffic ...

Is there a way to prevent links from opening in an iframe and have them open in the main window instead?

Imagine you have an iframe on your webpage: <iframe style="border-radius:15px;" width="190" height="450" frameborder="0" scrolling="no" marginheight="5" marginwidth="10" src="../img/interactive_map/interactive_sverige.htm"> </iframe> ...

How can I stop the page from jumping when a Button is clicked in ReactJS?

I've created a ShowcaseMovie component that fetches data using componentDidMount(), stores it in state, and renders Card components to display the data. The component also features four button elements for toggling between different filters: upcoming, ...

Customizing the appearance of a submenu header on a WordPress website

I need assistance in creating a sub-menu style. Please refer to the image linked below for guidance: Here is my website link: ...

Gradually vanishing words while they glide across the screen

I want to achieve a similar effect seen in the game A Dark Room. The text in the game serves two purposes which I am trying to replicate: The new text is added above the old text instead of below it, pushing the older text down the page as the game progr ...

Tips for reducing the impact on performance caused by cookie consent code

Experimenting with basic HTML to analyze the impact of cookie consent code. <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="description" content="determine page l ...

Checking randomly created email with Selenium

I have been tasked with creating test cases for a specific website, and I am using Selenium to automate the process of filling out a registration form. Everything is set up, but I am struggling to figure out how to validate the random email that has been e ...

Perfectly aligning the Update Progress Animation in real-time

I am currently utilizing the Ajax UpdateProgress with a loading gif attached. The issue I am facing is how to ensure that the loading.gif always appears in the center of the screen, even if the user is at the very top or bottom of the page. Is there a meth ...

Determine the placement of the body with CSS styling

Here is the code snippet from my website: body { background-image: url('background.jpg'); background-repeat: no-repeat; background-attachment: fixed; background-size: cover; } .centered { /* Center entire body */ display: flex; ...

Trigger the onClick event of an element only if it was not clicked on specific child elements

<div onClick={()=>do_stuff()}> <div classname="div-1"></div> <div classname="div-2"></div> <div classname="div-3"></div> <div classname="div-4"></div> ...

Eliminate styling that is specific to certain browsers

Recent browser updates have introduced new styling and functionality to input[type=number], including up and down buttons. In Chrome, I was able to eliminate this added styling by accessing the shadow DOM and identifying the specific element. However, de ...