EN
Google chrome dev tools xPath - list unique text elements in HTML
4
points
Hello everyone 👋 😊
In this post I would like to show you how to list unique text elements in HTML using chrome dev tools XPath utilities.
Quick into to Chrome XPath utilities.
$x(path, [startNode])
$x(path)
returns an array of DOM elements that match the given XPath expression.
For example, the following returns all the <p>
elements on the page:
$x("//p")
We can read more here: Chrome devtools console XPath utilities
Our practical example.
Our task is to list unique cities in HTML file.
Steps to test this example by yourself:
- Copy below html to file on our computer.
- Open html file in browser.
- Open google dev tools (F12).
- Open console in google dev tools.
- Copy + paste below xPath.
- We should see only 3 unique cities in console result.
Html code with all 6 cities and only 3 are unique San Francisco, New York, Los Angeles:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div class="city">San Francisco</div>
<div class="city">San Francisco</div>
<div class="city">New York</div>
<div class="city">San Francisco</div>
<div class="city">Los Angeles</div>
<div class="city">New York</div>
</body>
</html>
Chrome xPath:
[...new Set(($x("//div[contains(@class, 'city')]").map(value => (
value.textContent
))))]
Results, we have 3 unqiue cities:
["San Francisco", "New York", "Los Angeles"]
Screenshot with HTML file, chrome and chrome console results with XPath executed: