3

With Puppeteer, I know how to use evaluate for having some properties like parentNode or previousSibling:

let id = await page.evaluate(() => {
    let wantedHref = $('li a').filter(
        function (index) {
            return $(this).text().includes("Text that I Want");
        })[0];
    //get parentNode
    let id = wantedHref.parentNode.parentNode.parentNode.id;
    //get  previousSibling
    let expandIcon = wantedLink.parentNode.parentNode.previousSibling;
    expandIcon.click();
    return id;
});

I would like to know how I could retrieve these types of properties without using evaluation.

Could you help me, please?

Nmk
  • 1,281
  • 2
  • 14
  • 25
Pipo
  • 5,170
  • 7
  • 33
  • 66
  • The underlying CDP has [DOM.describeNode](https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-describeNode) command so it should be possible to use it in Puppeteer as well. See the documentation I've linked - the command returns a `Node` response with `parentId` inside which you can query in another `DOM.describeNode` or other commands that accept a node id. To find the original node you can use `DOM.querySelector`. – wOxxOm Mar 02 '20 at 16:15
  • Why don't you want to use evaluate? – hardkoded Mar 02 '20 at 16:29
  • @hardkoded I don't want to use evaluate cause it is more difficult to debug and to make pause , and anyway I would like to do this type of operation in several way – Pipo Mar 02 '20 at 16:38
  • @hardkoded I want to get all div with a specific class and get all id of their parent – Pipo Mar 02 '20 at 17:05
  • You could do a mix, use `$$` to get all the elements, and then an evaluate to get the parent of each element. – hardkoded Mar 02 '20 at 18:50

1 Answers1

7

elementHandle.getProperty('parentNode')

You can use elementHandle.getProperty() to obtain the parentNode property of the current ElementHandle:

const current_element = await page.$('#example');
const parent_node = await current_element.getProperty('parentNode');

await parent_node.click();
Grant Miller
  • 27,532
  • 16
  • 147
  • 165