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.
$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:
xxxxxxxxxx
1
$x("//p")
We can read more here: Chrome devtools console XPath utilities
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:
xxxxxxxxxx
1
2
<html lang="en">
3
<head>
4
<meta charset="UTF-8">
5
<title>Title</title>
6
</head>
7
<body>
8
9
<div class="city">San Francisco</div>
10
<div class="city">San Francisco</div>
11
<div class="city">New York</div>
12
<div class="city">San Francisco</div>
13
<div class="city">Los Angeles</div>
14
<div class="city">New York</div>
15
16
</body>
17
</html>
Chrome xPath:
xxxxxxxxxx
1
[...new Set(($x("//div[contains(@class, 'city')]").map(value => (
2
value.textContent
3
))))]
Results, we have 3 unqiue cities:
xxxxxxxxxx
1
["San Francisco", "New York", "Los Angeles"]
Screenshot with HTML file, chrome and chrome console results with XPath executed: