I want to get the values of "data id" using the class below and put them into an array.
<div data-id="111" class="tr svelte-1q11k9a" style="z-index: auto;">
<div data-id="222" class="tr svelte-1q11k9a" style="z-index: auto;">
<div data-id="333" class="tr svelte-1q11k9a" style="z-index: auto;">
I have tried this but it returned "undefined".
const ex = await page.$$eval("div[class='tr svelte-1q11k9a']", ({ data-id }) => data-id);
console.log(ex)
2
Answers
The issue lies in how you’re trying to extract the
data-id
attribute. The syntax for destructuring{ data-id }
is invalid because property names with hyphens cannot be directly destructured in JavaScript objects as it is used a minus operator.Try the below code, but I would prefer I you could name the attribute as
data_id
.To extract the values of
"data id"
attributes from the HTML elements and store them in an array, you can modify your code as shown below:This code uses
page.$$eval
to evaluate a function on all the matching elements and extract the "data-id" attribute value for each element usinggetAttribute('data-id')
. Then it usesmap
to create an array of these values.