EN
JavaScript / XPath - get preceding sibling element
9 points
In this short article we would like to show how to find using XPath, preceding sibling element reference in JavaScript.
In below example we are looking for preceding slibling (/preceding-sibling::input
) that occurs as previous of any label
element and contains Visible
text inside (//label[text()='Visible']
).
Quic solution:
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div id="element">
5
<label>
6
<input type="checkbox" checked />
7
<span>Visible</span>
8
</label>
9
</div>
10
<script>
11
12
var element = document.querySelector('#element');
13
14
var result = document.evaluate("//span[text()='Visible']/preceding-sibling::input", element);
15
var checkbox = result.iterateNext();
16
17
if (checkbox) {
18
console.log(checkbox.checked);
19
}
20
21
</script>
22
</body>
23
</html>