Now we have covered some common Xpath expressions we will look at moving around the inspector and stacking functions. If you are scripting on a website with dynamic elements you may find that there aren’t any suitable selectors however there is something more suitable in the immediate area. This is where: Following, Ancestor, Child, Preceding, Sibling, Parent, self and Descendant come in handy.
Following
//a[@type=’text’]//following::input
Following selects all the elements in the document of the current node. You can specify which tag name, attribute and value to select depending on the uniqueness of the elements .
Ancestor
//*[text()=‘In Stock’]//ancestor::div
Ancestor selects all the ancestor elements of the current node. This is primarily used if following/preceding don’t go far enough.
Child
//div[@id=loginform’]//child::input
Selects all children elements of the current node.
Preceding
//button[@type=’submit’]//preceding::input
Preceding selects all nodes that come before the current node.
Following-sibling
//*[@type=’submit’]//following-sibling::input
Selects the following siblings of the node. Siblings are the same level as the current node which can be extremely useful if there is a more effective selector nearby.
Parent
//div[@id=’rt-feature’]//parent::div
Selects the parent of the current node.
Self
//div[@type=’password’]//self::input
Selects the current node.
Descendant
//div[@id=’product’]//descendant::a
Selects the descendants of the current node.