Cheerio / jquery selectors: how to get a list of elements in nested divs?

I need to parse some markup like this from the html page:

<div id="list">

  <div class="item-level-a">
    <div class="item-level-b">
      <a href="http://www.example.com/1"></a>
    </div>
  </div>

  <div class="item-level-a">
    <div class="item-level-b">
      <a href="http://www.example.com/2"></a>
    </div>
  </div>

  <div class="item-level-a">
    <div class="item-level-b">
      <a href="http://www.example.com/3"></a>
    </div>
  </div>

</div>

I tried using this code:

$list = [];
$('div[id="list"]').each(function() {
  var href = $(this).find('div > div > a').attribs('href');
  list.push(href);
});

without success: error:

TypeError: Object <a href="http://www.example.com/1"></a>
                  <a href="http://www.example.com/2"></a>
                  <a href="http://www.example.com/3"></a>
has no method 'attribs'

: -. (

Any clue?

+4
source share
1 answer

In cheerioand jqueryyou get attributes with attr(), not attrib().

There are a few more problems with your code. Below is a working version using cheerio. This probably works in jquery.:

var list = [];
$('div[id="list"]').find('div > div > a').each(function (index, element) {
  list.push($(element).attr('href'));
});
console.dir(list);
+5
source

Source: https://habr.com/ru/post/1608037/


All Articles