How can I click on this element using XPATH in WebDriver with Java?

27,691

Solution 1

If the checkbox next to "Add Dexter" is what you want to click on the page, you can use:

Driver.findElement(By.xpath("//li[contains(.,'Add Dexter')]//input[@type='checkbox']")).click();

Solution 2

What is with this one:

  Driver.findElement(By.xpath("//input[@name='selectedMstrPrivGroupList[9].mstrAuthorities[0].status']")).click();

Solution 3

You can use like this, driver.findElement(By.xpath("//li[contains(text(),'Add Dexter')]")).click()

Solution 4

You can use xpath to click on the element as below:

driver.findElement(By.xpath("//input[text()='Add Dexter']")).click();

You can also click on that element by using cssSelector instead of xpath as below:

driver.findElement(By.cssSelector("input:contains(^Add Dexter$)")).click();

Note: CssPath/CssSelector is faster than xpath. So it's better to use cssSelector than xpath in most cases.

Share:
27,691
Mike
Author by

Mike

Working as Test consultant for a service oriented organization

Updated on February 08, 2020

Comments

  • Mike
    Mike over 4 years

    Here is the HTML:

    <li>
    <input type="checkbox" checked="" name="selectedMstrPrivGroupList[9].mstrAuthorities[0].status"/>
    Add Dexter
    </li>
    

    How could this element be clicked in WebDriver? It is a check box. And I want to use XPath as I have close to 30+ check boxes in the page. So that I can create a generic method and pass only the WebElement. I tried the following but didn't work.

    Driver.findElement(By.xpath("//input[contains(.,'Add Dexter')]")).click();
    
  • Mike
    Mike over 11 years
    Thanks for the quick response... This works in this case but I particularly don't want to use the name attribute. Reason: Page is dynamic and associated text changes frequently... So, I was looking for something with which i can click on the check box with its associated text... Thanks again!
  • Rajiv
    Rajiv over 11 years
    and if you want to make a generic method out of it, "//li[contains(.,'" + someString + "')]//input[@type='checkbox']" should work.
  • Mike
    Mike over 11 years
    This worked for me.. Thanks for the help.. Driver.findElement(By.xpath("//li[contains(.,'Add Dexter')]//input[@type='checkbox']")).click();