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.
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
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
Just try this
const parent_node = await child_node.getProperty('parentNode')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With