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):
xxxxxxxxxx
1
*[contains(.,'Text to find here')]
Where
Text to find here
should be replaced with text placed inside element we want to find.
Practical example:
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div id="container">
5
<label>
6
<input type="checkbox" checked />
7
Visible
8
</label>
9
</div>
10
<script>
11
12
var container = document.querySelector('#container');
13
14
var result = document.evaluate("*[contains(.,'Visible')]", container);
15
var element = result.iterateNext();
16
17
if (element) {
18
console.log(element.outerHTML);
19
}
20
21
</script>
22
</body>
23
</html>
By adding /*[@type='checkbox']
as postfix to previous expression we are able to find all checkbox
inputs.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div id="container">
5
<label>
6
<input type="checkbox" checked />
7
Visible
8
</label>
9
</div>
10
<script>
11
12
var container = document.querySelector('#container');
13
14
var result = document.evaluate("*[contains(.,'Visible')]/*[@type='checkbox']", container);
15
var checkbox = result.iterateNext();
16
17
if (checkbox) {
18
console.log(checkbox.checked);
19
}
20
21
</script>
22
</body>
23
</html>