This might be useful for someone else: Using this sample html
<div class="ParentDiv">
<label for="label">labelName</label>
<input type="button" value="elementToSelect">
</div>
<div class="DontSelect">
<label for="animal">pig</label>
<input type="button" value="elementToSelect">
</div>
If for example, I want to select an element in the same section (e.g div) as a label, you can use this
//label[contains(., 'labelName')]/parent::*//input[@value='elementToSelect']
This just means, look for a label (it could anything like a
, h2
) called labelName
. Navigate to the parent of that label (i.e. div class="ParentDiv"
). Search within the descendants of that parent to find any child element with the value of elementToSelect
. With this, it will not select the second elementToSelect
with DontSelect
div as parent.
The trick is that you can reduce search areas for an element by navigating to the parent first and then searching descendant of that parent for the element you need.
Other Syntax like following-sibling::h2
can also be used in some cases. This means the sibling following element h2
. This will work for elements at the same level, having the same parent.