user3525228
user3525228

Reputation: 103

XPath to select following-sibling

This is the code that I currently have:

<div>
<ul class="nav nav-pills nav-stacked">
<li>
<li>
<li>
<li>
<li>
<section>
<span name="merchant">ABZ</span>
</section>
<section>
<span class="glyphicon glyphicon-pencil" name="edit"></span>
<span class="glyphicon glyphicon-remove" name="delete"></span>
</section>
</li>
<li>
<li>
<li>
<li>
</ul>
<div class="add-item bottom" name="new-merchant">
</div>

I have tried the following:

xpath=//span[contains(.,'ABZ')]/following-sibling::section/span[@name='edit']
xpath=//span[contains(.,'ABZ')]/following-sibling::span[1]

I am using selenium, and I want it to click on the edit button that is right after the ABZ span.

Upvotes: 10

Views: 95279

Answers (2)

Mohit Arora
Mohit Arora

Reputation: 55

Adding to the answer above, both the expressions below will work well.

//span[contains(text(), 'ABZ')]/following::section/span[@name='edit']

OR

//span[contains(text(), 'ABZ')]/../following-sibling::section/span[@name='edit']

Notably, the axis following will pick each node following the context node while the axis following-sibling will only pick the sibling nodes to the context node.

Upvotes: 3

Richard
Richard

Reputation: 9019

This xpath worked for me in Chrome, using your html:

//span[contains(text(), 'ABZ')]/../following-sibling::section/span[@name='edit']

Edit

The .. means to go up a level. The .. takes the selector from span to section. Then the following-sibling finds the section after the parent section of your matching span.

Your original selector was matching span, then looking for a following-sibling to span.

Upvotes: 29

Related Questions