Search code examples
javascriptjquerynode.jscheerio

How do I get the value of the $ (this) .children inner element attribute?


There is such a library code Cheerio:

let outputTableBody = $('.box.table-quotes table.table tr').each(function(i, elem) {
   let expression = $(this).children('td:nth-child(1)').text();


   if(expression == companyNameArray[ExchangeNameParse]){
     $(this).children('td').each(function(i, elem) {
       if( i == 1 ){
         // do something
         }
       })
     }
})

In this example, I can pull out the text value of the td elements - regardless of whether there are additional parents there or not - the text will still be extracted correctly.

Question:
If such a tag (td) contains a child tag a - how can I extract the value of its href attribute in this construction?


Solution

  • You can use .find method to get the descendants of each element in the current set of matched elements, filtered by a selector - a in this case:

    ...
    const link = $(this).find('a').attr('href');
    ...