XPath Functions
When using XPaths in Selenium, there are a number of functions that can be used to speed up or improve our XPath, especially when talking about dynamic content.
PermalinkContains()
It is a method that is used in XPath expression and is used to locate the element with the partial text in the case where the text to be searched has too lengthy and the value of attribute changes dynamically on reload.
Example:
Xpath = //*[contains(@name='inputButton')]
PermalinkFollowing
This method selects all the elements of the current node in the HTML DOM structure.
Example:
Xpath=//*[@type='password']//following::input[1]
PermalinkAncestor
This method is used to select all the ancestor elements from the current node. The ancestor can be grandparents, parents of the current node in the HTML document.
Example:
Xpath=//*[text()='Introduction']//ancestor::div
It will find all the ancestors of the current web element matches the criteria of text()= ‘Introduction’ having the div tag.
PermalinkChild
This method is used in the scenarios in which we want to select the child elements of the current node in the HTML document.
Example:
Xpath=//*[@id='email']/child::div
PermalinkProceeding
This method is used to select all the nodes proceeding to the current node or the ones that come before the current node.
Example:
Xpath=//*[@type=button]//preceding::div
PermalinkFollowing-sibling
This method is used to locate the siblings which are at the same level as the current node.
Example:
Xpath=//*[@type=button]//following-sibling::div
PermalinkParent
This method is used to locate the parent of the current node in the HTML document.
Example:
Xpath=//*[@id=['password']//parent::li
PermalinkSelf
This method is used to locate itself in the HTML document. Self signifies the current node only.
Example:
Xpath=//*[@id='email']//self::input
PermalinkDescendant
This method is used to find the descendants of the current node in the HTML document.
Example:
Xpath=//*[@id='email']//descendant::a
PermalinkStart-with
This method is used in the scenarios when we want to match the starting text of the attributes and when we need to locate the web element when the attribute changes dynamically on refreshing and reload a web page.
Example:
Xpath=//label[starts-with(@name, 'mess_avg')]