Delivered by FeedBurner

Selecting Checkbox From Table Based On Preceding Or Following Sibling Column Value In WebDriver

Locating element's by Its own references Is easy but sometime you need to located them based on reference of other elements. Earlier we have learn how to locate checkbox based on Its position In THIS POST. Now I have one table and first column of table Is checkbox. 2nd column Is value(some
text) and based on that following sibling column's value(text), I wants to select check box from 1st column. I have this scenario In one of my current project. Same way, I have to select checkbox based on preceding sibling column's value(text). See Image bellow.

Here check box do not have Its own Identifier bet we have to Identify It based on related previous or next cell's text value. In this case, We can use sibling concept In XPath to locate preceding or following sibling element.

To select Dog checkbox, We have to use following-sibling In xpath as checkbox cell Is following to "Dog" text cell In table. So XPath to locate Dog checkbox Is as bellow.

  • //td[contains(text(),'Dog')] will locate "Dog" text cell.
  • /following-sibling will locate all siblings after the current node.
  • td/input[@type='checkbox'] will locate the checkbox

Here Is reverse condition. Checkbox comes first and value text comes last so concept Is same but we have to use word preceding-sibling In XPath as bellow.

  • //td[contains(text(),'Cow')] will locate "Cow" text cell.
  • /preceding-sibling will locate all siblings before the current node.
  • td/input[@type='checkbox'] will locate the checkbox
So now If you wants to write test to select above both textbox, It will be as bellow.
package Testing_Pack;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class Slibings {
 WebDriver driver;
 public void setup() throws Exception {
  driver =new FirefoxDriver();     
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
 public void selectCheck(){
  //Locating element using preceding-sibling In XPath.
  //Locating element using following-sibling In XPath.

You can use this sibling concept anywhere to locate any element like checkbox, radiobutton, textbox etc. If It Is dependent on other value.

1 comment:

  1. Hi,

    WebDriver driver = new FirefoxDriver();

    WebElement dTable= driver.findElement(By.xpath("//*[id='post-body-3107268830657760720']/div[1]/table/tbody"));

    Not able to locate this table. Please help...