Home > Web Front-end > JS Tutorial > body text

How can I use XPath to find HTML elements based on their inner text?

Patricia Arquette
Release: 2024-11-05 01:13:02
Original
486 people have browsed it

How can I use XPath to find HTML elements based on their inner text?

XPath: A Powerful Tool for Retrieving Elements Based on Inner Text

Locating specific elements within an HTML page can be a crucial task when working with web content. One common scenario is identifying elements based on the text they contain. To achieve this, XPath, a powerful language designed for navigating XML documents, offers an effective solution.

Finding an Element with Exact Inner Text

Consider an HTML snippet with an tag containing the text "SearchingText":

<a ...>SearchingText</a>
Copy after login

To retrieve this element using XPath, we can leverage the following query:

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

This expression navigates the document tree, locating any tag that contains the exact text "SearchingText." The text() function within square brackets compares the text content of the element to the specified string.

Handling Partial Text Matches

In certain cases, you may need to locate elements that contain partial matches of a given text. For instance, to find elements containing the text "Searching":

//a[contains(text(),'Searching')]
Copy after login

Here, the contains() function evaluates if the element's text content includes the provided substring. This approach allows for a broader search, capturing elements that may contain additional text.

Applying XPath in JavaScript

Integrating XPath with JavaScript provides a convenient approach to dynamically manipulate HTML documents. To demonstrate this, consider the following JavaScript code:

var xpath = "//a[text()='SearchingText']";
var matchingElement = document.evaluate(xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
Copy after login

This code assigns the XPath query to the xpath variable and then utilizes the document.evaluate() method to execute the query against the document object. The result is stored in the matchingElement variable, providing access to the element with the specified inner text.

The above is the detailed content of How can I use XPath to find HTML elements based on their inner text?. 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