How to Find HTML Elements by Text Content
If you have a known text within an HTML element, finding that element in the page can be useful. To accomplish this, you can leverage the power of XPath.
Using XPath to Find Elements by Text
XPath allows you to locate elements based on their text content. To find an element containing a specific text, use the following XPath syntax:
//element[text()='SearchText']
For example, to find an anchor tag containing the "SearchingText" text, you would use:
var xpath = "//a[text()='SearchingText']"; var matchingElement = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
Finding Elements Containing Partial Text
You can also search for elements that contain text partially using the "contains" function in XPath:
//element[contains(text(),'SearchText')]
This will find any anchor tag containing "SearchText" or any other text that includes "SearchText".
The above is the detailed content of How to Find HTML Elements by Their Text Content Using XPath?. For more information, please follow other related articles on the PHP Chinese website!