XPath: Using Preceding
XPath Preceding:
The preceding axis in XPath helps locate elements that appear before the current node in the document tree. In the examples below, the first XPath expression locates the input element for "email" that comes before the current node (in this case, the password field). The second example locates all elements that precede the current node.
This method is particularly useful for locating elements that cannot be accessed directly, such as in cross-browser testing. Sometimes, older or legacy browsers (like Internet Explorer) fail to recognize certain elements. In such cases, traversing elements using the preceding axis can help.
This selects the first input element that precedes the password field.
Example 1: XPath= //input[@name='password']//preceding::input[1]
This selects all input elements that precede the password field.
Example 2: XPath= //input[@name='password']//preceding::input
XPath Preceding-Sibling:
The preceding-sibling axis works similarly to the following-sibling axis, with the key difference being that it selects sibling nodes that appear before the current node, rather than after.
This allows you to switch between sibling nodes, starting from the context node and moving to one of its preceding siblings. Both nodes must share the same parent. For example, you can use the preceding-sibling axis to navigate from a "sign-up" link to a "login" link that appears before it in the document.
This selects the first li element that precedes the element with the class "login.
Example 1: XPath= //li[@class='login']//preceding-sibling::li[1]