EN
JavaScript / XPath - find any element that contains specific text
7
points
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>