Home >Web Front-end >JS Tutorial >How Do You Retrieve HTML Elements Based on Their Inner Text?
Getting Elements by InnerText: A Comprehensive Guide
Knowing the specific text contained within an HTML tag can be valuable in web development. This knowledge empowers developers to manipulate and interact with specific elements accurately. In this article, we will explore various methods for obtaining elements based on their inner text.
Method 1: Leveraging XPath
XPath (XML Path Language) offers a powerful and flexible approach for querying and navigating XML and HTML documents. It enables developers to retrieve elements based on specific criteria, including inner text.
Sample Code:
This code snippet retrieves the first element matching the XPath expression "//a[text()='SearchingText']", which selects any anchor tags containing the text "SearchingText." The matchingElement variable now holds a reference to the found element.
Method 2: Searching for Elements Containing Text
Alternatively, you can search for elements that contain (but do not necessarily exclusively contain) the specified text using XPath's "contains" function.
Sample Code:
This code returns an ordered list of all anchor tags in the document containing the substring "Searching." By iterating over the matchingElements list, you can access each individual element.
The above is the detailed content of How Do You Retrieve HTML Elements Based on Their Inner Text?. For more information, please follow other related articles on the PHP Chinese website!