Charvee Shah
Charvee Shah

Reputation: 720

Finding previous sibling element using selenium xpath dynamically

I am writing selenium scripts for the following code.

<div id="abc" class="ui-selectmanycheckbox ui-widget hpsapf-chechkbox">
     <div class="ui-chkbox ui-widget">
        <div class="ui-helper-hidden-accessible">
           <input id="abc:0" name="abc" type="checkbox" value="0" checked="checked">
        </div>
        <div class="ui-chkbox-box ui-widget ui-corner-all ui-state-default ui-state-active">
           <span class="ui-chkbox-icon ui-icon ui-icon-check ui-c"></span>
        </div>
     </div>
     <span class="hpsapf-radio-label">
        <label for="abc:0">Herr</label>
     </span>
     <div class="ui-chkbox ui-widget">
        <div class="ui-helper-hidden-accessible">
           <input id="abc:1" name="abc" type="checkbox" value="1">
        </div>
        <div class="ui-chkbox-box ui-widget ui-corner-all ui-state-default">
           <span class="ui-chkbox-icon ui-icon ui-icon-blank ui-c"></span>  
        </div>
     </div>
     <span class="hpsapf-radio-label">
        <label for="abc:1">Frau</label>
     </span>
</div>

These are the checkbox like the following.The number of the checkboxes are changed as per database values.

enter image description here

In my code i am first checking whether the "Frau" check box is selected or not. so i tried following snippet.

WebElement mainElement= driver.findElement(By.id("abc"));
WebElement label=mainElement.findElement(By.xpath(".//label[contains(@for,'abc')][text() = 'Frau']"));
WebElement parent = label.findElement(By.xpath(".."));
WebElement div = parent.findElement(By.xpath("preceding-sibling::::div"));
WebElement checkBox = div.findElement(By.className("ui-chkbox-box"));
String css = checkBox.getAttribute("class");
if(css.contains("ui-state-active")) {
    return "checked";
}
else
{
    return "unchecked";
}

But when i tried to execute this script. WebElement div = parent.findElement(By.xpath("preceding-sibling::::div")); gives me the first div tag and not the preceding one. I want a preceding sibling.

Upvotes: 4

Views: 10253

Answers (1)

Guy
Guy

Reputation: 50949

Use :: and index, not ::::

WebElement div = parent.findElement(By.xpath("preceding-sibling::div[1]"));

Upvotes: 8

Related Questions