skip to Main Content

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


  1. 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.

    const ex = await page.$$eval("div.tr.svelte-1q11k9a", (elements) => {
        return elements.map(el => el.getAttribute("data-id"));
    });
    console.log(ex);
    
    Login or Signup to reply.
  2. 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:

    const ids = await page.$$eval("div[class='tr svelte-1q11k9a']", elements => {
      return elements.map(element => element.getAttribute('data-id'));
    });
    
    console.log(ids);
    

    This code uses page.$$eval to evaluate a function on all the matching elements and extract the "data-id" attribute value for each element using getAttribute('data-id'). Then it uses map to create an array of these values.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search