Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cheerio / jquery selectors: how to get a list of elements in nested div's?

I need to parse some markup similar to this one, from an 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 did try with this code:

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

without success: error was:

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?

like image 663
MarcoS Avatar asked Sep 18 '15 14:09

MarcoS


People also ask

How to get attribute in cheerio?

Cheerio get element attributesAttributes can be retrieved with attr function. import fetch from 'node-fetch'; import { load } from 'cheerio'; const url = 'http://webcode.me'; const response = await fetch(url); const body = await response. text(); let $ = load(body); let lnEl = $('link'); let attrs = lnEl.

How jQuery selectors are executed?

jQuery selector: jQuery selectors are used to selecting the HTML element(s) and allow you to manipulate the HTML element(s) in a way we want. It selects the HTML elements on a variable parameter such as their name, classes, id, types, attributes, attribute values, etc. Example: HTML.

How many selectors are there in jQuery?

So far we have covered only three standard jQuery Selectors. For a complete detail of all these jQuery selectors, you can go to through jQuery Selectors Reference.


2 Answers

In cheerio and jquery, you get attributes with attr(), not attrib().

There are a few other problems with your code. Here is a working version using cheerio. It probably works in jquery this way as well.:

var list = [];
$('div[id="list"]').find('div > div > a').each(function (index, element) {
  list.push($(element).attr('href'));
});
console.dir(list);
like image 70
Trott Avatar answered Oct 13 '22 00:10

Trott


For those who prefer a functional style:

const list = $('div[id="list"]')
  .find('div > div > a')
  .toArray()
  .map(element => $(element).attr('href')));
like image 14
sdgfsdh Avatar answered Oct 13 '22 01:10

sdgfsdh