Skip to main content

Using xPath to reach parent of an element

Note: If you are new to java and selenium then start with selenium java training videos. 


I generally prefer CSS selectors over XPath when writing Selenium locators. CSS selectors are concise, readable, and usually provide everything I need.

However, there are situations where XPath is a better fit—particularly when I need to navigate through an element's hierarchy, such as moving from an element to its parent, grandparent, or sibling.

This post shows one such real-world example.

The Problem

I came across a situation where I needed to click a link based on the value of an input field.

The HTML structure contained multiple similar groups of elements. The input field and the link I wanted to click were not directly related, but they shared a common parent structure.

In the following example above, the input element is highlighted, and I need to click the corresponding anchor (<a>) element.

The challenge is that there may be multiple similar structures on the page. I therefore need to locate the link relative to the particular input element rather than using a fixed locator for the link itself.


Step 1: Navigate from the Input to Its Parent

First, I locate the input element based on its value attribute:

//input[contains(@value, '.')]

From this input element, I need to move up through two parent <div> elements.

XPath provides the parent axis for exactly this purpose:

//input[contains(@value, '.')]/parent::div/parent::div

This takes us from:

input
  ↓
parent div
  ↓
parent div

Step 2: Navigate to the Previous Sibling

Once I reach the required parent <div>, I need to move to its preceding sibling.

The XPath preceding-sibling axis allows us to do that:

//input[contains(@value, '.')]/parent::div
/parent::div/preceding-sibling::div

Now we have moved from the input element to the sibling <div> containing the link.

Step 3: Locate the Link

Finally, I can select the required anchor element:

//input[contains(@value, '.')]/parent::div
/parent::div/preceding-sibling::div/a[2]

The complete navigation can therefore be visualized as:

input
  ↓
parent div
  ↓
parent div
  ↓
preceding sibling div
  ↓
second anchor

This is one of the situations where XPath becomes particularly useful. Instead of relying on a unique ID, class, or other attribute on the target link, we locate it relative to another element that we can identify reliably.

A Shorter XPath

I originally posted this question to the WebDriver Google Group, where Luke suggested a shorter XPath:

//input[contains(@value, '.')]/../..
/preceding-sibling::div/a[2]

This achieves essentially the same result.

Instead of explicitly using the parent::div axis twice:

/parent::div/parent::div

we can simply use:

/../..

So:

//input[contains(@value, '.')]/parent::div
/parent::div/preceding-sibling::div/a[2]

becomes:

//input[contains(@value, '.')]/../..
/preceding-sibling::div/a[2]

Personally, I find the first version more descriptive because it makes the XPath axes explicit. The shorter version is more compact, but both are valid approaches.

XPath Axes Worth Knowing

This example also demonstrates several useful XPath axes:

  • parent — moves to the parent of the current element.
  • preceding-sibling — selects siblings that appear before the current element.
  • following-sibling — selects siblings that appear after the current element.
  • ancestor — moves to any ancestor element.
  • descendant — selects elements contained within the current element.

Understanding these axes can make XPath much more powerful when dealing with complex or dynamically generated HTML.



<script type="text/javascript">
    
<div id="holder_55007" class="voucher clear">

    <div class="left">

        <div class="left notes">

            <a class="openTestLink"
               rel="http://REDACTED"
               href="javascript:void(0);">
            </a>

            <br>
            <br>

            <a title="Yes, it works"
               href="javascript:void(0);">
            </a>

            <a title="No, it doesn't work. Set it as expired."
               href="javascript:void(0);">
            </a>

            <br>
            <br>

            <input id="skipCoupon_55007"
                   class="skipClass"
                   type="checkbox"
                   name="skipCheck_55007"
                   value="">

            <label for="skipCoupon_55007">
                skip
            </label>

            <br>

            <span>30.02.2011 05:37</span>

            <br>
            <br>

            <hr>

        </div>

    </div>

    <div class="left couponmainarea2">

        <textarea id="titleInput_55007"
                  class="v2titleInput vtip editTitle"
                  readonly=""
                  title="Click to edit title"
                  name="coupon_title_55007">
        </textarea>

        <div class="left couponmainarea2">
        </div>

        <div class="left couponmainarea2">

            <input id="exp_date_55007"
                   class="expiry_date"
                   type="text"
                   value="31.10.2011"
                   name="expiry_date_55007">

            <div class="date_selector"
                 style="display: block; top: 441px; left: 15px;">

                <a id="REDACTED_55007"
                   class="sortOrange"
                   href="javascript:void(0);">
                </a>

                <input id="unknown_expiry_55007"
                       class="unknown_expiry"
                       type="checkbox"
                       name="unknown_expiry_55007"
                       value="1">

            </div>

        </div>

    </div>

</div>




CSS or XPath?

I still prefer CSS selectors whenever they can express the relationship clearly.

However, XPath is extremely useful when the locator needs to navigate through the DOM rather than simply identify an element.

When this article was originally written, CSS selectors did not provide a practical way to move from an element to its parent. Modern CSS has since evolved and supports the :has() relational pseudo-class, which can express some relationships that previously required XPath.

Even so, XPath remains an important tool in a Selenium engineer's toolbox—especially when you need explicit DOM navigation using axes such as parent, ancestor, or preceding-sibling.

The lesson is not “always use XPath.”

It is:

Use the simplest locator that reliably expresses the relationship you need.

For straightforward element identification, CSS is often my first choice. When the relationship between elements becomes more complex, XPath can be the cleaner solution.



Popular posts from this blog

Verify email confirmation using Selenium WebDriver

Note: If you are new to java and selenium then start with selenium java training videos .   How to Verify Email Confirmation Using Selenium 4 and JavaMail (2026 Guide) Email confirmation is a critical part of most registration flows — account activation, password reset, multi-factor authentication, and onboarding. Every automation engineer eventually faces the same challenge: How do you verify an email confirmation link inside a Selenium test without making it slow and flaky? The wrong instinct is to automate Gmail's UI with Selenium. It's fragile, slow, and breaks constantly. The right approach: Use Selenium for browser automation Use JavaMail (IMAP) to read the email directly Extract the confirmation link Continue the test in Selenium Why Not Automate Gmail UI With Selenium? Automating the Gmail UI means logging in, searching, clicking a message, and parsing content from a third-party interface that changes frequently. This leads to: Flaky...

Real Time JMeter Result Using Backend Listener

Since JMeter 2.13 Backend Listener has been available to create real time graph of JMeter Test. Following tutorial explain the entire process in detail. At the end of this tutorial you would be able to create JMeter Live Test Result dashboard similar to following - This tutorial borrows information from many sources and my own experiments with JMeter live reporting dashboard. I have added source of information wherever applicable But before we can build such a snazzy JMeter Live Reporting dashboard we need to understand two more components - influxDB (a time series database) and Grafana Dashboard This is a big tutorial, so take deep breath :-) and follow on. Once you complete set up specified in this tutorial then you can watch JMeter Training Video Tutorial to watch this in action. What is Time Series Database? A time series is a sequence of data points , typically consisting of successive measurements made over a time interval . Examples of time ...