jquerynode.jsnightmare

Not getting values from jQuery loop


I'm trying to get the text and the link of an element on a website using Nightmare.js and jquery.

I'm looping through every element with the same class, I get no error, but the text and link are empty.

Here is what I tried:

nightmare
        .goto("https://myanimelist.net/anime/season")
        .wait(2000)
        .evaluate(() => {
            let links = [];

            $('.link-title').each(() => {
                item = {
                    "title": $(this).text(),
                    "link": $(this).attr("href")
                };
                links.push(item);
            });

            return links;   
        })
        .end()
        .then(result => {
            console.log(result);
        })
        .catch(function (error) {
            console.error('Failed', error);
        });

The output in the console looks like this:

[ { title: '' }, 
  { title: '' },
  { title: '' },
  ... 99 more items 
]

Solution

  • $('.link-title').each(() => {
                item = {
                    "title": $(this).text(),
                    "link": $(this).attr("href")
                };
                links.push(item);
            });
    

    Inside each() method, use normal function instead. Arrow functions make this not work as you expected