In web development, it often becomes necessary to manipulate or access specific HTML elements based on the text they contain. This is particularly useful for automating UI testing, data scraping, and content analysis.
One way to retrieve HTML elements by their inner text is through the powerful XPath language. XPath allows you to query an HTML document using a combination of node selectors and predicates.
To get an HTML element based on its exact inner text, you can use the following XPath expression:
//elementName[text()='innerText']
For instance, to get the a tag that contains the text "SearchingText":
var xpath = "//a[text()='SearchingText']"; var matchingElement = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
Alternatively, you can search for elements that contain specific text, regardless of whether it's an exact match, using the following XPath expression:
//elementName[contains(text(), 'searchText')]
For example, to get all a tags that contain the text "Searching":
var xpath = "//a[contains(text(),'Searching')]";
The above is the detailed content of How to Retrieve HTML Elements Based on Their Inner Text Using XPath?. For more information, please follow other related articles on the PHP Chinese website!