use cheerio to get a list of attributes

Viewed 6846

I want to get ['http://www.1.com', 'http://www.2.com', 'http://www.3.com'] from following string.

const cheerio = require('cheerio')

const htmlStr = `
<div>

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

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

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

</div>
`

const $ = cheerio.load(htmlStr)

Initially, I thought $(div.item a) will return an array of elements. So I tried with :

const urls = $('div.item a').map(x => x.attr('href'))

It failed.

Seems $('div.item a') returns an object.

How to do that?

Thanks!

2 Answers

First of all, cheerio's map function takes a callback where the first argument is the current index, not element that again must be wrapped in $(…). Next, map returns a "jQuery set", not a vanilla JavaScript array. Use toArray:

$('div.item a').map((i, x) => $(x).attr('href')).toArray()

figure out another way:

$('div.item a').get().map(x => $(x).attr('href'))

get() retrieve all elements matched.

Related