Search code examples
javascriptarraysnode.jscheerio

How to get child of div in cheerio


I am working with cheerio and I am stuck at a point where I want to get the href value of children div of <div class="card">.

<div class="Card">  
   <div class="title">
    <a target="_blank" href="test">
        Php </a>
    </div>
    <div>some content</div>
    <div>some content</div>
    <div>some content</div>
 </div>

I got first childern correctly but i want to get div class=title childern a href value. I am new to node and i already search for that but i didn't get an appropriate answer.

var jobs = $("div.jobsearch-SerpJobCard",html);

here is my script

 const rp = require('request-promise');
 const $  = require('cheerio');
 const potusParse = require('./potusParser');
 const url = "";

 rp(url)
   .then((html)=>{
     const Urls = [];
      var jobs = $("div.Card",html);


      for (let i = 2; i < jobs.length; i++) {
         Urls.push(
                $("div.Card  > div[class='title'] >a", html)[i].attribs.href
     );
   }
  console.log(Urls);


   })

     .catch(err => console.log(err));

Solution

  • It looks something like this:

    $('.Card').map((i, card) => {
      return {
        link: $(card).find('a').text(),
        href: $(card).find('a').attr('href'),
      }
    }).get()
    

    Edit: the nlp library is chrono-node and I also recommend timeago.js to go the opposite way