How to verify an attribute is present in an element using Selenium WebDriver?

Viewed 77361

I have many radio buttons on my screen. When a radio button is selected, it has an attribute of checked. When the radio button is not selected, the checked attribute is not present. I would like to create a method that would pass if the element is not present.

I am using selenium webdriver and java. I know I can retrieve attributes by using getSingleElement(XXX).getAttribute(XXX). I'm just not sure how to verify that an attribute does not exist, and for the test to pass when it doesn't exist (fail if it does exist).

When the radio button is checked

<input id="ctl00_cphMainContent_ctl00_iq1_response_0" type="radio" name="ctl00$cphMainContent$ctl00$iq1$response" value="1" checked="checked"> 

When the radio button is not checked

<input id="ctl00_cphMainContent_ctl00_iq1_response_0" type="radio" name="ctl00$cphMainContent$ctl00$iq1$response" value="1">

I want the test to pass when the checked attribute is not present

7 Answers

as none of the answers helped me I would like to share the very simple solution I went with in the end:

static ExpectedCondition<Boolean> isAttributePresent(WebElement element, String attrName) {
    JavascriptExecutor executor = (JavascriptExecutor) getDriver();
    String script = "return arguments[0].getAttributeNames();";
    var attributes = executor.executeScript(script, element);
    return input -> ((ArrayList) attributes).contains(attrName);
}

I hope it helps someone. I used it for wait.until(condition) scheme

Related