Languages
[Edit]
EN

Google chrome dev tools xPath - list unique text elements in HTML

4 points
Created by:
Root-ssh
115270

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:

  1. Copy below html to file on our computer.
  2. Open html file in browser.
  3. Open google dev tools (F12).
  4. Open console in google dev tools.
  5. Copy + paste below xPath.
  6. 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:

 

JavaScript - Blog posts

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join