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

How to Find HTML Elements by Their Text Content Using XPath?

Patricia Arquette
Release: 2024-11-05 15:15:02
Original
862 people have browsed it

How to Find HTML Elements by Their Text Content Using XPath?

How to Find HTML Elements by Text Content

If you have a known text within an HTML element, finding that element in the page can be useful. To accomplish this, you can leverage the power of XPath.

Using XPath to Find Elements by Text

XPath allows you to locate elements based on their text content. To find an element containing a specific text, use the following XPath syntax:

//element[text()='SearchText']
Copy after login

For example, to find an anchor tag containing the "SearchingText" text, you would use:

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

Finding Elements Containing Partial Text

You can also search for elements that contain text partially using the "contains" function in XPath:

//element[contains(text(),'SearchText')]
Copy after login

This will find any anchor tag containing "SearchText" or any other text that includes "SearchText".

The above is the detailed content of How to Find HTML Elements by Their Text Content 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!