Search code examples
xpathselenium-webdriverdidselectrowatindexpathdomxpathxpathnavigator

xpath queries to find closest element


I am working on project with java and selenium webdriver 2.44, we need the closest element of text. For example I have email text on page and i need the closest element that is text box. I have run the below given xpath query on facebook.com. However, it finds numbers of input type that is email and text. We do not need jQuery to run as we are using selenium webdriver.

.//*[contains(text(),'Email')]/following::input[@type='email' or @type='text']

Can anyone provide me xpath query to find closest element on page. Or a tutorial site where I can learn how to query. enter image description here


Solution

  • Not a perfect solution, though in facebook scenario u can find first element as:

    (.//*[contains(text(),'Email')]/following::input[@type='email' or @type='text'])[1]
    

    Another thing to add if you are getting multiple elements for your query you can use:

    List<WebElement> txtList = new ArrayList<WebElement>();
    txtList = driver.findElements(By.xpath(".//*[contains(text(),'Email')]/following::input[@type='email' or @type='text']"));
    

    and use txtList.get(0).sendKeys("abcd");