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

Methods for smoothly animating an image to move up and down using CSS

I'm new to CSS and I was wondering if it's possible to create a smooth vertical movement effect for an image using CSS. Something like shown in this link: .... ...

PHP and Bootstrap combine in this dynamic carousel featuring thumbnail navigation

Looking to create a dynamic bootstrap carousel with image thumbnails at the bottom? After exploring various code snippets and solutions, I stumbled upon this link. While the code worked, I found the thumbnails to be too small. Below are the functions I use ...

Adding an external font with CSS in Bootstrap 5 can be quite challenging

Hey there, I'm a newcomer around here and I could use some help with my post. It might not be perfect, but any guidance you can offer would be appreciated. The issue I'm facing is that I'm having trouble getting the font I downloaded or lin ...

Achieving 5-star ratings on Google through Selenium with Python

I'm attempting to leave a 5-star review for a location on Google Maps. I've successfully written the comment, but I am unable to select the stars. Here is the code snippet I used to submit the comment and give 5 stars: WebDriverWait(driver, 10). ...

Can you explain the significance of this HTML code?

While examining some source code, I came across the following: <div class="classname {height: 300px; width: 200px}"></div> I am aware that element styling can be done using the style="" attribute. Could you explain what this code snippet sig ...

Execute with jQuery using Multiple Attribute Selector

I am attempting to input numeric values using a keyboard. My issue is as follows: the keyboard has an "Accept" button, and I have multiple text fields. I want to assign a different action for each text field. I attempted to use multiple attribute selector ...

Unable to select selectbox in the bottom section of Safari browser

There seems to be an issue with the selectbox being unselectable at the lower part in Safari. It's difficult to pinpoint the exact problem in the code. You can see the issue on the country selectbox by visiting this website: <span> <sp ...

Button with small width containing an icon and text

I am trying to create a simple HTML button that has an icon on top and a description below it. <div class="mybtn"> <div><img src="someimage.png"></div> <div>Button description</div> </div> My question is, ...

How to centrally position an image within a cropped parent container using CSS

Is there a way to center an img within a parent div tag that has overflow: hidden set? I am looking to clip the image equally on both sides in order to display the middle portion. <div class='wrapper'> <img/> </div> The desi ...

What's causing ng-show to malfunction in IE11 on AngularJS?

I am experiencing a strange issue with my code - ng-show works perfectly fine on Firefox, but not on IE 11. <div ng-show="isExist" class="panel panel-default"> Here is the relevant code snippet from the controller: $scope.isExist = false; if(user ...

Setting Image Height with CSS

I have a div with a height of 105px. The image inside the div is 359px tall. How can I adjust the div's size to prevent cutting off the image and ensure it displays in full height? Thank you for your help! ...

What could be causing my HTML table to resize images from left to right?

My latest attempt at creating a simple HTML table involved filling it with placeholder images and spacing them out using a background color. However, the end result was not what I expected: https://i.sstatic.net/kyRil.png Upon closer examination, you&apo ...

A guide to selecting the dropdown item labeled as (Select All) using Python and Selenium

edit: Trying to submit parameters for a database-generated report on this page. Successfully modified the start date in the first field using send_keys(), but unable to click on "(Select All)" for fields 3 and onwards, except one. In order to access the h ...

Content and footer being covered by the sidebar

I have an illustration here to help explain my issue. The problem I am facing is that the Sidebar is overlapping both my Content and Footer when the content consists of only small items. In my _layout file, I'm referencing the sidebar like thi ...

Designing a slider to display a collection of images

I am currently working on a slider project using HTML, javascript, and CSS. I'm facing an issue where only the first two images (li) are being displayed and it's not transitioning to the other (li) elements. Below is the HTML code snippet: <se ...

Creating a design that resembles boxes for the div elements while ensuring the grid layout remains undisturbed

Hey there! I'm new to using Bootstrap and I'm trying to create boxes that look like the ones on the right side of this page: Unfortunately, I haven't had much luck so far. I tried using padding, but it messed up my grid system. I assigned a ...

The background of the body isn't showing up on the

I'm having trouble setting the background on my page. The background works for another div on the same page, but not on the body background itself. <!DOCTYPE HTML> <html> <head> <title>iDeas.com</title> <link rel=" ...

Tips for maximizing website performance on touch-enabled devices

When using a touch device such as an iPhone, iPad, or Android device, it can be challenging to accurately tap on small buttons with your finger. So far, there is no universal method in CSS media queries to detect touch devices. As a workaround, I check if ...

Looking to create an infinite loop in Python that continuously imports another file while utilizing Selenium?

I am trying to run a program every 30 seconds, but it seems that every time I try to execute the code it stops after running it just once... Currently, I have a single .py file (named: loop) that contains the loop. Within this loop, another .py file (name ...

Selenium encountered difficulty in navigating to the newly opened tab

I have a project in progress where I am developing a tool to streamline the process of sharing videos on various platforms and social media. My plan is to utilize Python and Selenium as a Webdriver to automate clicking on the share button for YouTube video ...