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?
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.
The querySelector() method is available on the document object or any Element object.
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.
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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With