Public
Edited
Dec 21, 2024
Insert cell
# Xpath

- [document.evaluate()](https://developer.mozilla.org/en-US/docs/Web/API/Document/evaluate)
- [Xpath - MDN](https://developer.mozilla.org/en-US/docs/Web/XPath)


## document.evaluate()
The main interface to using XPath is the evaluate function of f the document object.

```javascript
const xpathResult = document.evaluate(
xpathExpression,
contextNode,
namespaceResolver,
resultType,
result,
)
```
- `xpathExpression`: A string containing the XPath expression to be evaluated.
- `contextNode`: A node in the document against which the `xpathExpression` should be evaluated, including any and all of its child nodes. The document node is the most commonly used.
-
Insert cell
## Playground
Insert cell
Insert cell
Insert cell
Insert cell
{
window.__xpath_target?.forEach?.((n) => {
if (n.nodeName == "#text") {
n = n.parentElement;
}
n.classList.remove("xpath-highlight");
});
const t1 = Date.now();
const xpathResult = document.evaluate(
xpath,
document,
null,
XPathResult.ANY_TYPE,
null
);
let nodes = [];
let node = null;
while ((node = xpathResult.iterateNext())) {
nodes.push(node);
}

nodes.forEach((n) => {
if (n.nodeName == "#text") {
n = n.parentElement;
}
n.classList.add("xpath-highlight");
});
window.__xpath_target = nodes;

return nodes;
}
Insert cell
document.evaluate(xpath, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotItem(0)
Insert cell
## ancestor
Insert cell
<div>
<div data-a="">
<li data-a="1"></li>
<span data-a="d">
<h2 id="target-002" data-a="d" ></h2>
</span>
</div>
</div>
Insert cell
{
const target = document.querySelector("#target-002");
const result = document.evaluate(
"ancestor-or-self::*[@data-a]",
target,
null,
XPathResult.ORDERED_NODE_ITERATOR_TYPE,
null
);

const list = [];
let node = null;
while ((node = result.iterateNext())) {
list.push(node);
}

return list;
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more