【问题标题】:JavaScript evaluate XPATH within an element?JavaScript 评估元素内的 XPATH?
【发布时间】:2021-07-08 20:32:45
【问题描述】:

我正在尝试使用 document.evaluate() 获取元素,但也想仅在特定元素中进行搜索。比如:

const element = document.evaluate('.//p', ...); //I want this to return the Hello, World p element
<html>
  <body>
    <div id="someId">
      <p>Hello, World!<p>
    </div>
  </body>
</html>

有什么方法可以将 id 为 someId 的 div 传递到评估中以仅在该范围内搜索?

我知道我可以编写整个 XPATH,例如 .//div[@id="someId"]/p (不适用于我的情况)或进行字符串连接,但我想找到一种更简洁的方法,比如传递某处的 DOM 元素(或它包含的某个对象)。

【问题讨论】:

    标签: javascript html dom xpath


    【解决方案1】:

    这正是document.evaluate()的第二个参数的目的:

    contextNode 指定查询的上下文节点(请参阅XPath specification)。将文档作为上下文节点传递是很常见的。

    const someId = document.getElementById('someId');
    
    const result = document.evaluate('.//p', someId, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null)
    
    console.log(result.snapshotItem(0)); // Hello, World!
    console.log(result.snapshotItem(1)); // null
    <div id="someId">
      <p>Hello, World!</p>
    </div>
    <div>
      <p>Goodbye, World!</p>
    </div>

    【讨论】:

      【解决方案2】:

      您还可以将document 用于contextNode,使用查询中的父ID(如您所问)。像这样:

      const snapshotType = XPathResult.ORDERED_NODE_SNAPSHOT_TYPE;
      const result1 = document.evaluate('.//div[@id="someId"]//p', document, null, snapshotType);
      
      console.log(`result1 contains ${result1.snapshotLength} element, namely`, result1.snapshotItem(0))
      
      //alternatively search for the actual text
      const result2 = document.evaluate('.//p[contains(text(), "Hello")]', document, null, snapshotType);
      
      console.log(`result2 contains ${result2.snapshotLength} element, namely`, result2.snapshotItem(0));
      
      // finally, if the element order is fixed, you can take the first one
      const result3 = document.evaluate('(.//p)[1]', document, null, snapshotType);
      console.log(`result3 contains ${result3.snapshotLength} element, namely`, result3.snapshotItem(0));
      <div id="someId">
        <p>Hello, World!</p>
      </div>
      <div>
        <p>Goodbye, World!</p>
      </div>
      <div>
        <p>And I left</p>
      </div>

      【讨论】:

        猜你喜欢
        • 2010-11-27
        • 1970-01-01
        • 1970-01-01
        • 2023-03-24
        • 1970-01-01
        • 2013-11-04
        • 2010-11-03
        • 1970-01-01
        • 2018-03-31
        相关资源
        最近更新 更多