简体   繁体   中英

Traverse from Child Node to Ancestor Node using XPath in Selenium WebDriver

I am trying to traverse to the ancestor node from a child node using xpath, but it does not want to work.

WebElement menuItemText = driver.findElement(By.xpath("//span[contains( text(), '" + itemTitle + "')]"));
menuItemText = menuItemText.findElement(By.xpath(".//parent::*[@attribute='onclick']"));
menuItemText.click();

The nodes is:

<div onclick="something()">
  <div onclick="myFunction()">
    <div>
      <div>
        <span>Text!</span>
      </div>
    </div>
  </div>
</div>

However, the function name is very complex and each node has strange unique IDs. Not that it should matter too much but I want to traverse up the DOM from the child node to the parent / ancestor node that includes an onclick attribute. I want to get the first onclick when traversing up the DOM. So, the onclick=myFunction() is what I want to get.

Is that possible? I tried doing a while() loop and it worked for once but not anymore.

您可以通过使用ancestor关键字直接从子节点访问祖先元素,如下所示:

//span[contains(text(),\"Text\")]/ancestor::div[@onclick]

I hope any of the following will solve the issue. ie) it will select the first ancestor div that contains attribute on click.

1: //span[contains(text(),\"Text\")]/ancestor::div[@onclick][1]
2: (//span[contains(text(),\"Text\")]/ancestor::div[@onclick])[1]

To search for the element with text as Text! and referencing it to locate the <div> tag with onclick attribute as myFunction() , you have to induce WebDriverWait for the elementToBeClickable and you can use the following based Locator Strategy :

  • xpath :

     new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//span[contains(., '" + itemTitle + "')]//preceding::div[starts-with(@onclick, 'myFunction')]"))).click();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM