Sammar Ahmad
Sammar Ahmad

Reputation: 246

How to get all elements in a list in puppeteer

I have a page container having list of folders. I want to click them one by one. Attached is the screenshot of the page with page source. enter image description here

I have tried the below code:

   let elements = document.getElementsByClassName('document-container')

   for (let element of elements)
   {
    await  element.click();
   }
    

But this does not work.

Upvotes: 1

Views: 5066

Answers (2)

theDavidBarton
theDavidBarton

Reputation: 8851

You could use page.$$ to collect all instances of the .document-container elements as element handles. It runs document.querySelectorAll in the page's context.

Then you are able to iterate the clicks with elementHandle.click (as you've already tried it).

const elHandleArray = await page.$$('.document-container')

for (const el of elHandleArray) {
  await el.click()
}

Upvotes: 1

smmehrab
smmehrab

Reputation: 876

Where have you initiated the current page, using puppeteer? You gotta use page.click(elementToClick);.

Here, you are trying to get the elements inside the specified div. That means, you need to get the children of the specified container div.

To get all children of a HTML element, You can always use .children property, which will return the array of elements inside another element. And will return an empty array, in case the parent element has no child.

In your code, you may try something like this:

let container = document.getElementByClassName('document-container');

let elements = container.children;

for(element in elements){
  element.click();
}

See if it works.

Upvotes: 0

Related Questions