'How do I get parent and siblings of ElementHandle in NodeJS?
I have a ElementHandle, and not its selector, how do I get its Parent and Siblings as ElementHandle.
I know that given selector of the Element, it can be done using
const item = document.querySelector(query);
const parent = item.parentElement;
Don't know what to do if I have ElementHandle instead of its selector. Please help.
Solution 1:[1]
You can use elementHandle.$x() to evaluate an XPath expression relative to the elementHandle to obtain the parent and siblings of your given element:
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
Solution 2:[2]
Although this question is tagged puppeteer, it comes up first in Google for similar searches with "Playwright".
For those who are using Playwright, you can use a similar solution (adopted from the 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
Solution 3:[3]
Just try this
const parent_node = await child_node.getProperty('parentNode')
Solution 4:[4]
try this
const parentElement = await exampleElement.evaluateHandle(
(element) => element?.parentElement?.parentElement?.parentElement?.parentElement?.parentElement,
);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | Leo Wilbur |
| Solution 4 |
