XPathResult:snapshotItem() 方法
snapshotItem() 方法是 XPathResult 介面的一個方法,它返回快照集合中的一個項,如果索引超出了節點的範圍,則返回 null。與迭代器結果不同,快照不會失效,但如果文件被修改,它可能不再對應於當前文件。
語法
js
snapshotItem(i)
引數
i-
一個數字,表示項的索引。
返回值
位於 XPathResult 節點集中給定索引處的 Node。
異常
TYPE_ERR
如果 XPathResult.resultType 不是 UNORDERED_NODE_SNAPSHOT_TYPE 或 ORDERED_NODE_SNAPSHOT_TYPE,則會丟擲型別為 TYPE_ERR 的 DOMException。
示例
以下示例演示了 snapshotItem() 方法的用法。
HTML
html
<div>XPath example</div>
<div>Tag names of the matched nodes: <output></output></div>
JavaScript
js
const xpath = "//div";
const result = document.evaluate(
xpath,
document,
null,
XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
null,
);
let node = null;
const tagNames = [];
for (let i = 0; i < result.snapshotLength; i++) {
node = result.snapshotItem(i);
tagNames.push(node.localName);
}
document.querySelector("output").textContent = tagNames.join(", ");
結果
規範
| 規範 |
|---|
| DOM # dom-xpathresult-snapshotitem-index-index |
瀏覽器相容性
載入中…