Dhiwakar Ravikumar
Dhiwakar Ravikumar

Reputation: 2217

How To Construct An XPATH With Condition Matching A Preceding Sibling's Child

I need to select the element <a> only if the preceding <li>'s text value is LINE 2

    <html>
 <div>
  <label>LABEL 1</label>
   <div>
    <ul>
     <li>LINE ITEM 1</li>
    </ul>
   </div>
   <div>
     <div>
       <a>Edit</a>
     </div>
   </div>
 </div>
 <div>
  <label>LABEL 2</label>
   <div>
    <ul>
     <li>LINE ITEM 2</li>
    </ul>
   </div>
   <div>
     <div>
       <a>Edit</a>
     </div>
   </div>
 </div>
</html>

In the above HTML document, the actual number of can vary based on design changes, what remains a constant are the values of the line items <li>

I want an XPATH query which will fetch the Edit immediately following the line item whose value is LINE ITEM 2

I have tried some of the suggestions given below but I can't get it to work.

Upvotes: 0

Views: 105

Answers (3)

Jack Fleeting
Jack Fleeting

Reputation: 24930

Try something like this and see if it works:

//a[ancestor::div[.//ul/text()="LINE 2"]]

Edit:

//a[text()="Edit"][ancestor::div[.//li[text()="LINE ITEM 2"]]]

Upvotes: 0

DSte
DSte

Reputation: 1

Try this maybe:

a[ancestor::div/preceding-sibling::ul/descendant::li[normalize-space(text())='LINE 2']]

Not sure of the structure of you want in terms of elements though.

Upvotes: 0

DonnyFlaw
DonnyFlaw

Reputation: 690

Please check this XPATH-expression

//ul[li="LINE 2"]/following-sibling::div/a

In case you don't know on which level li located you can use

//li[.="LINE ITEM 2"]/following::a[.="Edit"]

Upvotes: 1

Related Questions