How to select grand-grand child (Like 5th OR 6th grand child) element using xpath which has class name only

106 Views Asked by At

I am trying to select a 5th or 6th grand child which do not have any other attributes other than class name. Please check below example DOM.

<div id="abc abc abc">
  <a>
    <a>
      <a>
        <a>
          <a>
</div>

Can I find last Fifth a using xpath?? Don't want to use something like //div/a/a/a/a/a

1

There are 1 best solutions below

0
Alejandro On

The inside a predicate, the position() fuction works against the locator step axis. That is called proximity position. So this XPath expression:

//div[@id='abc abc abc']/descendant::a[5]

Meaning:

Select the fifth a element descendant of such div element

That expression with this wellformed input:

<div id="abc abc abc"> 
  <a> 
    <a> 
      <a> 
        <a> 
          <a id="target"/> 
        </a> 
      </a> 
    </a> 
  </a> 
</div>

Selects:

<a id="target"/>

Test in here