Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 935
steven Avatar asked Sep 05 '18 07:09

steven


3 Answers

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
like image 193
Grant Miller Avatar answered Oct 28 '22 06:10

Grant Miller


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
like image 9
rinogo Avatar answered Oct 28 '22 06:10

rinogo


Just try this

const parent_node = await child_node.getProperty('parentNode')
like image 3
Leo Wilbur Avatar answered Oct 28 '22 08:10

Leo Wilbur