Home >Web Front-end >JS Tutorial >How to Retrieve HTML Elements Based on Their Inner Text Using XPath?

How to Retrieve HTML Elements Based on Their Inner Text Using XPath?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-06 02:20:02952browse

How to Retrieve HTML Elements Based on Their Inner Text Using XPath?

Getting HTML Elements by Inner Text

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.

Selecting Element by Exact Text

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;

Selecting Element Containing Text

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn