Union find
Union find

Reputation: 8150

Nested each loop selections with Cheerio

I'm trying to do a nested each loop with Cheerio, selecting my Cheerio selection twice. I've written my code this way because I want to iterate on the number of parent selections, while making a secondary selection.

My second each loop does not find any elements. I've also tried creating a new cheerio $$ constructor and feeding the html into it, but that fails as well.

$(selector1).each(function (i, el) {
    j++;
    // logging html is showing several p elements
    console.log($(this).html());
    $(this).find('p').each((k, elem) => {
      // but this loop is not finding any elements
      // $(elem).text() returns null
    });
  });

Upvotes: 2

Views: 2442

Answers (1)

Union find
Union find

Reputation: 8150

Was able to get it to work with the following. For whatever reason, I had to reselect the child each loop's element to get its innerText. For the parent element, I was able to just call text() on the argument.

const $ = cheerio.load(res);
  const data = [];
  $(selector1).each((i, el) => {
    j++;
    $(el).find('p').each((k, elem) => {
        // i had to reselect $(elem) here rather than just use elem.text()
      data.push({
        text: $(elem).text(),
        post: j
      });
    });
  });

Upvotes: 2

Related Questions