Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a Dynamic Element by Selector

I need to click to a certain web button with the id: #product-6852370-Size.

I am working with Puppeteer, so normally I would do:

page.click('#product-6852370-Size');

The tricky part is that the number 6852370 is dynamic and changes every time I refresh the page.

So what I need is a piece of code that is saying:

Search for id's that include product- and -size. Any way that this might happen?

like image 218
Typhoon Avatar asked Jul 21 '18 18:07

Typhoon


People also ask

What does the querySelectorAll () method do?

The querySelectorAll() method in HTML is used to return a collection of an element's child elements that match a specified CSS selector(s), as a static NodeList object. The NodeList object represents a collection of nodes. The nodes can be accessed by index numbers.

Can you use querySelector on an element?

The querySelector() method is available on the document object or any Element object.

How do I get the value of a querySelector?

Use document. querySelector('selector') to Get Input Value in JavaScript. The document. querySelector('selector') uses CSS selectors which means, it can select elements by id, class, tag name, and name property of the DOM element.


1 Answers

You can match the beginning and end of the id attribute using:

await page.click('[id^="product-"][id$="-Size"]');

Or, more accurately, you can ensure that a number is present in the middle of your id using regex:

await page.evaluate(() => {
  [...document.querySelectorAll('[id^="product-"][id$="-Size"]')].filter(e => e.id.match(/^product-\d+-Size$/g))[0].click();
});
like image 75
Grant Miller Avatar answered Oct 26 '22 23:10

Grant Miller