Languages
[Edit]
EN

JavaScript / XPath - find any element that contains specific text

7 points
Created by:
Giles-Whittaker
739

In this short article we would like to show how using XPath expression, JavaScript and built-in web browser API, find any element referece that contains specifinc text.

Quicki solution (XPath expression):

*[contains(.,'Text to find here')]

Where Text to find here should be replaced with text placed inside element we want to find.

Practical example:

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <div id="container">
    <label>
      <input type="checkbox" checked />
      Visible
    </label>
  </div>
  <script>
    
    var container = document.querySelector('#container');

    var result = document.evaluate("*[contains(.,'Visible')]", container);
    var element = result.iterateNext();

    if (element) {
      console.log(element.outerHTML);
    }
    
  </script>
</body>
</html>

Checkbox input with text node example

By adding /*[@type='checkbox'] as postfix to previous expression we are able to find all checkbox inputs.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <div id="container">
    <label>
      <input type="checkbox" checked />
      Visible
    </label>
  </div>
  <script>
    
    var container = document.querySelector('#container');

    var result = document.evaluate("*[contains(.,'Visible')]/*[@type='checkbox']", container);
    var checkbox = result.iterateNext();

    if (checkbox) {
      console.log(checkbox.checked);
    }
    
  </script>
</body>
</html>
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript / XPath

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