In the HTML code like this:

<a class="test-class">
    <div class="test-content">
        <div class="test-time" data-start="12:13pm" data-full="12:13 PM - 12:50 PM">
            <span>12:13pm - 12:50pm</span>
        <div class="test-title">Classes Name</div>
    <div class="test-bg"></div>

I am trying to click <a class="test-class"">. However, I need to locate that element by text 12:13pm - 12:50pm from <span>12:13pm - 12:50pm</span> , which is not visible from front-end.

Is there a way to get XPath of <a class="test-class"">?

3 Answers 3


If you want to match the "a" element you would need to use ancestor

//span[text()='12:13pm - 12:50pm']/ancestor::a[@class='test-class']
  • Cool! It works for me! Thx for your help!
    – Lehtia
    Commented Jun 30, 2017 at 23:12

As per the code shared above, any of the following two x-paths can be used to locate the element by using the text mentioned in the question.

To search element by exact text:

 //a[@class='test-class']//span[text()='12:13pm - 12:50pm']


Below x-path is for like search. This will give you flexibility to use unique part of the text

(in case, there are multiple elements with similar text).

//a[@class='test-class']//span[contains(text(),'12:13pm - 12:50pm')]
  • Thx for your help. But when i try to use this xpath, i am not able to locate the element as it is not visible. As i mentioned in the question, the text is not visible for front-end, i think it might be the reason. But @George McConnon 's answer works for me.
    – Lehtia
    Commented Jun 30, 2017 at 23:15
  • Sorry mate. But, I am glad that the other answer worked for you and your problem is resolved.
    – Aalok
    Commented Jul 1, 2017 at 2:29

Agree with above answers. Wanted to add few points:

Solution 1 -

  • This solution is working currently with me.

    driver.findElement(By.xpath("//div[. = '12:13pm - 12:50pm']")).click();
  • But its has one barrier. Can't user for other than english's some special characters. Avoided in next solution 2

Solution 2 -

  • This is good fit solution if you are using string or text with special characters, white spaces.

    String label = "12:13pm - 12:50pm";
    String string = String.format("//button[contains(.,'%s')]", label);
  • I got solution from here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.