Skip to content
CodeKruPro

Move from a child to its parent with XPath

Automation taskMediumAsked in: Accenture, Infosys

Asked as: "The element you need has no stable attribute, but a child or sibling has one. How do you reach it?" The page is a tree: every element sits inside a parent, and elements with the same parent are siblings. XPath axes walk that tree from an element you can find: parent:: goes one level up, ancestor:: any number of levels up, and following-sibling:: to later elements with the same parent. In this task you find the strong element inside the paragraph with id boldText, print its text, then move up to its parent and print the parent id.

XPath Axes - Parent and Sibling

XPath Axes

XPath axes let you navigate the DOM tree relative to an element:

  • parent:: - parent element
  • following-sibling:: - next sibling
  • preceding-sibling:: - previous sibling
  • ancestor:: - any ancestor
  • descendant:: - any descendant

On the Text Messages page, the bold text (id="boldText") has a <strong> child element.

HTML Structure:

<p id="boldText">
  <strong>A Bold Text</strong>
</p>

The <strong> is a child of the <p>. XPath axes let you traverse this relationship in both directions.

Task:

  1. Navigate to https://testkru.com/Elements/TextMessages
  2. Find the <strong> element inside #boldText using descendant XPath
  3. Print the strong element's text
  4. From the <strong> element, navigate to its parent and print the parent's ID

Expected output:

Strong text: A Bold Text
Parent ID: boldText
Read full tutorial on Codekru