1

I am having hard time with identifying if radio option No is selected or not using Selenium Java. Below is the screenshot of the radio options on the web page. A workable solution is much appreciated.

enter image description here

Below is the HTML code. ::after (highlighted below) gets dynamically loaded when No option is selected.

enter image description here

I created below Java method that executes JavaScript that I am expecting to return whole label tag. It is currently printing out null. However, when I execute the script used below in Chrome browser console, it identifies the entire label tag including ::before and ::after pseudo elements.

public String whichRadioOptionIsSelected() {
        String tag = "";
        List<WebElement> radioOptions = findElementsByXpath(".//div[@id='ButtonOptions']/label");

        for(int i = 1; i <= radioOptions.size(); i++) {
                String script = "return document.querySelector('div#ButtonOptions > label:nth-of-type("+i+") label', null);";
                JavascriptExecutor js = (JavascriptExecutor) driver;
                tag = (String) js.executeScript(script);
                System.out.println(tag);
            }        
        return tag;
    }
  • what happens when u use isSelected() on input tag – PDHide Jun 28 at 17:00
  • Hello @PDHide, I created a separate method that used isSelected() and it always returned 'false'. Here is the code that I tried: java public boolean whichRadioOptionSelected() { boolean isNoSelected = false; if (isElementPresent(conditionTrue)) { WebElement noOption = findElementByXpath(RADIO_NO); if (noOption.isSelected()) { isNoSelected = true; } else { isNoSelected = false; } } return isNoSelected; } – skota Jun 28 at 19:26
  • why to create separe method when u already have inbuilt method – PDHide Jun 28 at 21:34
  • What was the xpath in radio_no – PDHide Jun 28 at 22:07
0

Try this:

public String whichRadioOptionIsSelected() {
        try {
            WebElement selectedOption = findElementByXpath("//div[@id='ButtonOptions']//input[@value='true']/following-sibling::label");
            if(selectedOption.isPresent())
                return selectedOption.getText();
        }
        catch(Exception e) {
            return null;
        }       
    }
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.