Home >Web Front-end >JS Tutorial >How to Retrieve HTML Elements by Their Inner Text Using XPath?
Retrieving HTML Elements by Inner Text
Identifying and accessing HTML elements based on their text content can be a common task in web development. This article explores a method to efficiently retrieve an element using its inner text.
Solution Using XPath
One effective approach to get an element by its inner text is through XPath. XPath is a language designed to navigate XML and HTML documents, and it provides powerful expressions for element selection based on various criteria.
For the given HTML example:
<code class="html"><a ...>SearchingText</a></code>
You can use the following XPath expression to get the anchor element:
//a[text()='SearchingText']
This expression selects all a elements containing the exact text SearchingText. To retrieve the first matching element:
<code class="javascript">var xpath = "//a[text()='SearchingText']"; var matchingElement = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;</code>
Partial Text Matching
In cases where you only know part of the element's text, you can use the contains() function in the XPath expression:
//a[contains(text(),'Searching')]
This expression selects all a elements containing the substring Searching anywhere within their text.
By leveraging XPath's capabilities, you can efficiently retrieve HTML elements based on their inner text, enabling you to perform various tasks such as data extraction or dynamic element manipulation.
The above is the detailed content of How to Retrieve HTML Elements by Their Inner Text Using XPath?. For more information, please follow other related articles on the PHP Chinese website!