如何使用document.evaluate()和XPath获取元素列表? [英] How to use document.evaluate() and XPath to get a list of elements?

查看:1332
本文介绍了如何使用document.evaluate()和XPath获取元素列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用document.evaluate() JavaScript方法来获取XPath表达式指向的元素:

I'm using the document.evaluate() JavaScript method to get an element pointed to by an XPath expression:

var element = document.evaluate(
  path,
  document,
  null,
  XPathResult.FIRST_ORDERED_NODE_TYPE,
  null
).singleNodeValue;

但是,如果XPath表达式指向页面上的多个元素,该如何获取元素列表?

But how do I get a list of elements in case the XPath expression points to more than one element on the page?

我尝试了以下代码,但没有用:

I tried the following code, but it is not working:

var element = document.evaluate(
  path,
  document,
  null,
  XPathResult.ORDERED_NODE_ITERATOR_TYPE,
  null
);

推荐答案

我在原型库.

I found the following solution in the book I am currently reading. It says that the code is from the Prototype library.

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;
}

像这样使用它:

let items = getElementsByXPath("//*"); // return all elements on the page

这篇关于如何使用document.evaluate()和XPath获取元素列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆