0

I have a div that contains a set of dynamic elements. I want to click on the first search result.

Here is what the HTML looks like.

I want to click on the first element contains in

I tried using creating a custom xPath like so but it didn't work. Any ideas here?

//div[1][contains(text(), 'listing')]
theodoros
  • 13
  • 2
  • you can give unique id to to your container div and could do something like: document.body.getElementyById(id).firstChild. However, I would recommend you to use null check before this to avoid exceptions. – berkayaytek Dec 05 '22 at 11:44
  • @berkayaytek Thank you for your reply. Ideally I would like to pass which child to get in a variable. I thought doing something like this I.executeScript(`var elements = document.getElementById('listing_63398541');elements[${listingNum}].click();`); but I'm getting undefined. I'm not able to locate the listing – theodoros Dec 05 '22 at 11:55

2 Answers2

0

First of all It would've helped if you had provided more information.

best will be using pseudo-child like div.firstChild or if the elements are generated dynamically you can add a class and use document.querySelectorAll(".class") which will give you an array of elements that had the class.

You can use array[0] to use click on the first element.

Tohirul Islam
  • 334
  • 1
  • 9
0

For anyone coming across this thread here is the solution

const listings = await page.$x('//*[contains(@id,"listing_")]')

theodoros
  • 13
  • 2