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
Release: 2024-11-06 02:20:02
Original
951 people have browsed it

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']
Copy after login

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;
Copy after login

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')]
Copy after login

For example, to get all a tags that contain the text "Searching":

var xpath = "//a[contains(text(),'Searching')]";
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template