【问题标题】:How do I get parent and siblings of ElementHandle in NodeJS?如何在 NodeJS 中获取 ElementHandle 的父级和兄弟级?
【发布时间】:2026-01-28 15:35:01
【问题描述】:

我有一个 ElementHandle,而不是它的选择器,我如何将它的 Parent 和 Siblings 作为 ElementHandle。

我知道给定元素的选择器,可以使用

const item = document.querySelector(query);
const parent = item.parentElement;

如果我有 ElementHandle 而不是它的选择器,我不知道该怎么办。请帮忙。

【问题讨论】:

    标签: javascript jquery node.js puppeteer


    【解决方案1】:

    您可以使用elementHandle.$x() 评估相对于elementHandle 的XPath 表达式,以获得给定元素的父元素和兄弟元素:

    const example = await page.$('#example'); // Element
    const example_parent = (await example.$x('..'))[0]; // Element Parent
    const example_siblings = await example.$x('following-sibling::*'); // Element Siblings
    

    【讨论】:

      【解决方案2】:

      虽然这个问题被标记为 puppeteer,但它在 Google 中以“Playwright”进行类似搜索时出现在首位。

      对于正在使用 Playwright 的人,您可以使用类似的解决方案(来自answer provided by @grant-miller):

      const example = await page.$('#example'); // Element
      const example_parent = await example.$('xpath=..'); // Element Parent
      const example_grandparent = await example.$('xpath=../..'); // Element Grandparent
      const example_siblings = await example.$$('xpath=following-sibling::*'); // Element Siblings
      

      【讨论】:

      • 亲爱的,谢谢你写这篇文章。它今天出现在我的谷歌搜索中。 ?
      【解决方案3】:

      试试这个

      const parent_node = await child_node.getProperty('parentNode')
      

      【讨论】:

      • 感谢您提供此代码 sn-p,它可能会提供一些有限的即时帮助。 proper explanation 将通过展示为什么这是解决问题的好方法,并使其对有其他类似问题的未来读者更有用,从而大大提高其长期价值。请edit您的回答添加一些解释,包括您所做的假设。
      【解决方案4】:

      试试这个

      const parentElement = await exampleElement.evaluateHandle(
          (element) => element?.parentElement?.parentElement?.parentElement?.parentElement?.parentElement,
      );
      

      【讨论】:

      • 请不要只发布代码作为答案,还要解释您的代码的作用以及它如何解决问题的问题。带有解释的答案通常更有帮助、质量更好,并且更有可能吸引投票。
      最近更新 更多