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

How to Retrieve HTML Elements by Their Inner Text Using XPath?

Mary-Kate Olsen
Release: 2024-11-04 20:24:02
Original
939 people have browsed it

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

You can use the following XPath expression to get the anchor element:

//a[text()='SearchingText']
Copy after login

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

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

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!

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