Home > database >  Convert javascript code to puppeteer with .pop method
Convert javascript code to puppeteer with .pop method

Time:03-02

I'm new to puppeteer and I try to convert this javascript code :

       
       let messageElement;
       await driver.findElements(By.className("message-list-item")).then(
           (ok) => {
            messageElement = ok.pop()
           }
       )
      

    
        await messageElement.getAttribute("id").then(
            (ok) => {
                messageNum = parseInt(ok.split("message")[1]);
            }
        )
       

The ".pop()" method need to be convert and I know with puppeteer we can use "length - 1" but I can't. I've tried this :

const el = await page.$('.message-list-item')
  .then( (elements) => elements[el.length - 1]);

But not work.

Can you help me ? Thanks in advance.

CodePudding user response:

This has nothing to do with "converting .pop() to puppeteer". pop is a standard function on the Array prototype. According to the puppeteer docs, the page.$(<selector>) performs a querySelector on the DOM nodes, which returns the DOM node directly rather than an array of DOM nodes, so you don't need to use pop or any other Array function.

const el = await page.$('.message-list-item')
  .then( (element) => element));

which is equivalent to

const el = await page.$('.message-list-item');

CodePudding user response:

let messageElement = (await page.$$('.message-list-item'))[0]
let messageElementID = await page.evaluateHandle(element => element.id, messageElement)
messageNum = parseInt(messageElementID.split("message")[1])
  • Related