Get elements by XPath – JavaScript

作者: zengde 分类: 笔记 发布时间: 2021-11-24 03:43

数组

function getElementsByXPath(xpath, parent) {
  let results = [];
  let query = document.evaluate(xpath, parent || document,
      null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  for (let i = 0, length = query.snapshotLength; i < length; ++i) {
      results.push(query.snapshotItem(i));
  }
  return results;
}
const $elements = getElementsByXPath("//span[contains(., 'ADDED')]");

单个元素

function getElementByXpath(path) {
  return document.evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
}

console.log( getElementByXpath("//html[1]/body[1]/div[1]") );

参考:

1、https://developer.mozilla.org/en-US/docs/Introduction_to_using_XPath_in_JavaScript#document.evaluate

2、https://developer.mozilla.org/en-US/docs/Web/API/Document.evaluate