Say I have the following UL:
<ul>
<li>barry</li>
<li>bob</li>
<li>carl</li>
<li>dave</li>
<li>roger</li>
<li>steve</li>
</ul>
I need to grab all the LIs between bob & roger. I can grab everything after bob with //ul/li[contains(.,"bob")]/following-sibling::li
, and I can grab everything before roger with //ul/li[contains(.,"roger")]/preceding-sibling::li
. The problem is when I try to combine the two, I end up getting extra results.
For example, //ul/li[contains(.,"bob")]/following-sibling::li[contains(.,"roger")]/preceding-sibling::li
will of course get everything before roger, instead of ignoring the items before bob.
Is there a way to chain these two xpaths together?
The preceding-sibling axis indicates all the nodes that have the same parent as the context node and appear before the context node in the source document.
To traverse to the next sibling, we have to use the following-sibling concept in xpath. This will allow us to traverse to the next sibling from the present sibling of the same parent. Let us try to move from the first child<h1> of parent <div> to the second <h2> as in the above image.
We can find an element using the xpath locator with Selenium webdriver. To identify the element with xpath, the expression should be //tagname[@attribute='value']. To identify the element with xpath, the expression should be //tagname[@class='value']. There can be two types of xpath – relative and absolute.
So, we will first find the XPath of the current node. XPath(Current node): //input[@id = 'text']. We will then find the XPath of the parent element node of the current node using parent syntax, as shown below screenshot. XPath of the Parent node: //input[@id = 'text']//parent::span.
Try:
/ul/li[preceding-sibling::li='bob' and following-sibling::li='roger']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With